0


Spring boot 与redis 群集

以下是使用Spring Boot与Redis集群进行交互的代码示例:

  1. 添加Redis依赖:
    • pom.xml文件中添加Spring Data Redis依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
  1. 配置Redis集群:
    • application.propertiesapplication.yml文件中配置Redis集群的连接信息,例如:

spring.redis.cluster.nodes=host1:port1,host2:port2,host3:port3

  1. 使用RedisTemplate进行操作:
    • 创建一个Redis的操作类,例如RedisService,并注入RedisTemplate对象:
 import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.data.redis.core.RedisTemplate;
   import org.springframework.stereotype.Service;

   @Service
   public class RedisService {

       private final RedisTemplate<String, String> redisTemplate;

       @Autowired
       public RedisService(RedisTemplate<String, String> redisTemplate) {
           this.redisTemplate = redisTemplate;
       }

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

       public String getValue(String key) {
           return redisTemplate.opsForValue().get(key);
       }
   }
  1. 使用RedisService进行操作:
    • 在需要使用Redis的地方,注入RedisService对象并调用相应的方法:
 import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.web.bind.annotation.GetMapping;
   import org.springframework.web.bind.annotation.PathVariable;
   import org.springframework.web.bind.annotation.RequestMapping;
   import org.springframework.web.bind.annotation.RestController;

   @RestController
   @RequestMapping("/redis")
   public class RedisController {

       private final RedisService redisService;

       @Autowired
       public RedisController(RedisService redisService) {
           this.redisService = redisService;
       }

       @GetMapping("/{key}")
       public String getValue(@PathVariable String key) {
           return redisService.getValue(key);
       }
   }

在上述示例中,我们通过注入RedisTemplate对象来操作Redis集群。在RedisService中,我们定义了一些常用的操作方法,例如setValue()getValue(),用于设置和获取Redis的键值对。

RedisController中,我们使用RedisService来处理相关的请求,例如通过/redis/{key}路径获取Redis中的值。

确保你的Redis集群已正确配置,并替换示例代码中的相应信息,如Redis集群节点的主机和端口等。


本文转载自: https://blog.csdn.net/canduecho/article/details/131602355
版权归原作者 田猿笔记 所有, 如有侵权,请联系我们删除。

“Spring boot 与redis 群集”的评论:

还没有评论