SpringBoot连接Redis集群案例

梦里梦外; 2023-07-21 05:52 141阅读 0赞

一、安装redis集群

可以参考:Redis-cluster集群案例

二、新建SpringBoot项目

1)、导入案例需要的pom依赖

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3htMzkzMzkyNjI1_size_16_color_FFFFFF_t_70

2)、添加配置

  1. spring:
  2. redis:
  3. database: 0
  4. password: 123456
  5. jedis:
  6. pool:
  7. max-active: 8
  8. max-wait: -1
  9. max-idle: 8
  10. min-idle: 0
  11. timeout: 10000
  12. cluster:
  13. nodes:
  14. - 192.168.1.122:9001
  15. - 192.168.1.122:9002
  16. - 192.168.1.122:9003
  17. - 192.168.1.122:9004
  18. - 192.168.1.122:9005
  19. - 192.168.1.122:9006

3)、编写测试代码

封装redis:

  1. /** springboot 2.0 整合redis
  2. * @program: testrediscluster
  3. * @description:
  4. * @author: HQ Zheng
  5. * @create: 2020-04-02 16:56
  6. */
  7. @Component
  8. public class RedisService {
  9. @Autowired
  10. private StringRedisTemplate stringRedisTemplate;
  11. public void set(String key, Object object, Long time) {
  12. // 让该方法能够支持多种数据类型存放
  13. if (object instanceof String) {
  14. setString(key, object);
  15. }
  16. // 如果存放时Set类型
  17. if (object instanceof Set) {
  18. setSet(key, object);
  19. }
  20. // 设置有效期
  21. if (time != null) {
  22. stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
  23. }
  24. }
  25. public void setString(String key, Object object) {
  26. String value = (String) object;
  27. // 存放string类型
  28. stringRedisTemplate.opsForValue().set(key, value);
  29. }
  30. public void setSet(String key, Object object) {
  31. Set<String> valueSet = (Set<String>) object;
  32. for (String string : valueSet) {
  33. stringRedisTemplate.opsForSet().add(key, string);
  34. }
  35. }
  36. public String getString(String key) {
  37. return stringRedisTemplate.opsForValue().get(key);
  38. }
  39. }

测试接口:

  1. /**
  2. * @program: testrediscluster
  3. * @description: 测试Redis集群
  4. * @author: HQ Zheng
  5. * @create: 2020-04-02 16:56
  6. */
  7. @RestController
  8. public class IndexController {
  9. @Autowired
  10. private RedisService redisService;
  11. @RequestMapping("/setString")
  12. public String setString(String key, String value) {
  13. redisService.set(key, value, 60l);
  14. return "success";
  15. }
  16. @RequestMapping("/get")
  17. public String get(String key) {
  18. return redisService.getString(key);
  19. }
  20. }

4)、测试结果

添加测试值key=test100,value=12345

20200402170333114.png

获取测试key=test100

20200402170359194.png

整合成功

发表评论

表情:
评论列表 (有 0 条评论,141人围观)

还没有评论,来说两句吧...

相关阅读