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);
    }
}
相关推荐
William一直在路上几秒前
SpringBoot 拦截器和过滤器的区别
hive·spring boot·后端
慌糖1 分钟前
CentOS 安装 Redis 简明指南
linux·redis·centos
小马爱打代码1 小时前
Spring Boot 3.4 :@Fallback 注解 - 让微服务容错更简单
spring boot·后端·微服务
旷世奇才李先生1 小时前
奇哥面试记:SpringBoot整合RabbitMQ与高级特性,一不小心吊打面试官
spring boot·面试·java-rabbitmq
经典19922 小时前
spring boot 详解以及原理
java·spring boot·后端
R_AirMan2 小时前
深入浅出Redis:一文掌握Redis底层数据结构与实现原理
java·数据结构·数据库·redis
Hello.Reader3 小时前
RedisJSON 内存占用剖析与调优
数据库·redis·缓存
白仑色3 小时前
Spring Boot 多环境配置详解
java·spring boot·后端·微服务架构·配置管理
超级小忍3 小时前
在 Spring Boot 中优化长轮询(Long Polling)连接频繁建立销毁问题
java·spring boot·后端
Z_W_H_4 小时前
【springboot】IDEA手动创建SpringBoot简单工程(无插件)
java·spring boot·intellij-idea