springboot 搭建一个 测试redis 集群连通性demo

背景:我需要用 springboot 建一个测试 redis 集群连通性的 demo

废话不多说直接上代码:

1.pom

xml 复制代码
</dependency>
			<!-- Spring Boot Starter Data Redis -->
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-data-redis</artifactId>
			</dependency>
			<!-- Jedis Client for cluster support -->
			<dependency>
				<groupId>redis.clients</groupId>
				<artifactId>jedis</artifactId>
			</dependency>

2.配置

yaml 复制代码
spring:
  application:
    name: demo
  redis:
    cluster:
      nodes:
        - 10.228.48.28:26379,10.228.48.19:26379,
        - 10.228.48.21:26379,10.228.48.28:26380,
        - 10.228.48.19:26380,10.228.48.21:26380
    password: 0666AAcuSl_VLC8e
    timeout: 10000
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0

3.建一个 config 类

java 复制代码
package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author wangjn
 * @Description
 * @createTime 2024-06-13 10:44:00
 */
@Service
public class RedisClusterService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void setValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public String getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}

4.controller

java 复制代码
package com.example.demo;

import com.example.demo.config.RedisClusterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author wangjn
 * @Description
 * @createTime 2024-06-13 10:49:00
 */
@RestController
public class RedisController {

    @Autowired
    private RedisClusterService redisClusterService;

    // 设置Redis键值对
    @PostMapping("/redis/set/{key}")
    public String setValue(@PathVariable("key") String key, @RequestBody String value) {
        redisClusterService.setValue(key, value);
        return "Value set successfully for key: " + key;
    }

    // 获取Redis中的值
    @GetMapping("/redis/get/{key}")
    public String getValue(@PathVariable("key") String key) {
        return redisClusterService.getValue(key);
    }
}
相关推荐
Mr. zhihao2 小时前
深入解析redis基本数据结构
数据结构·数据库·redis
辰海Coding3 小时前
MiniSpring框架学习-完成的 IoC 容器
java·spring boot·学习·架构
柿柿快乐5 小时前
Redis 入门第一课:全局命令、内部编码与单线程模型
redis·学习·缓存·基础教学
Tirzano7 小时前
超大型组和用户缓存redis
redis·缓存·哈希算法
阿维的博客日记7 小时前
zset实现延迟队列
redis·zset
无小道8 小时前
Redis——string类型相关指令
redis·指令·string
Maiko Star8 小时前
* SpringBoot整合LangChain4j
java·spring boot·后端·langchain4j
绝知此事9 小时前
【产品更名】通义灵码升级为 Qoder CN:AI 编码助手新时代,附大模型收费与 Spring Boot 支持全对比
人工智能·spring boot·后端·idea·ai编程
linmoo19869 小时前
Agent应用实践之四 - 基础:AgentScope-SpringBoot集成源码解析
人工智能·spring boot·agent·agentscope·openclaw
码云骑士9 小时前
Redis 入门实战:从 NoSQL 概念到安装与基础操作详解(一)
数据库·redis·缓存