spring boot下JedisCluster方式连接Redis集群

本文详细介绍了如何在Spring Boot项目中配置并使用Redis集群,包括Gradle配置、application.yml配置、自定义配置类、JedisCluster连接配置及Redis帮助类的实现与使用,同时提供了使用Spring Data Redis进行操作的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.首先是引入配置文件

      

1

2

gradle方式的配置文件

compile 'redis.clients:jedis:2.9.0'

2.application.yml的配置

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

spring:

  application:

    name: xxxx

  session:

    store-type: redis

  redis:

    password: xxxxx

    clusterNodes: xxxxxxx

    expireSeconds: 120

    commandTimeout: 10000  #redis操作的超时时间

    pool:

     maxActive: 5000 #最大连接数

     maxIdle: 30 #最大空闲连接数

     minIdle: 5 #最小空闲连接数

     maxWait: 3000  #获取连接最大等待时间 ms  #default -1

3.新增类RedisProperties

1

2

3

4

5

6

7

8

9

@Component

@ConfigurationProperties(prefix = "spring.redis")

public class RedisProperties {

 

    private int    expireSeconds;

    private String clusterNodes;

    private String password;

    private int    commandTimeout;

}

4.JedisCluster方式连接集群的配置

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

@Configuration

public class JedisClusterConfig {

 

    @Autowired

    private RedisProperties redisProperties;

 

    /**

     * 注意:

     * 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用

     * @return

     */

    @Bean

    public JedisCluster getJedisCluster() {

        String[] serverArray = redisProperties.getClusterNodes().split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)

        Set<HostAndPort> nodes = new HashSet<>();

 

        for (String ipPort : serverArray) {

            String[] ipPortPair = ipPort.split(":");

            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));

        }

 

        return new JedisCluster(nodes,redisProperties.getCommandTimeout(),1000,1,redisProperties.getPassword() ,new GenericObjectPoolConfig());//需要密码连接的创建对象方式

    }

 

}

5.redis帮助

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

<br>@Component

public class RedisUtil {

    private static final Logger LOGGER    = LoggerFactory.getLogger(RedisUtil.class);

 

    @Autowired

    private JedisCluster  jedisCluster;

 

    /**

     * 设置缓存

     * @param key    缓存key

     * @param value  缓存value

     */

    public void set(String key, String value) {

        jedisCluster.set(key, value);

        LOGGER.debug("RedisUtil:set cache key={},value={}", key, value);

    }

 

    /**

     * 设置缓存对象

     * @param key    缓存key

     * @param obj  缓存value

     */

    public <T> void setObject(String key, T obj , int expireTime) {

        jedisCluster.setex(key, expireTime, JSON.toJSONString(obj));

    }

 

    /**

     * 获取指定key的缓存

     * @param key---JSON.parseObject(value, User.class);

     */

    public String getObject(String key) {

        return jedisCluster.get(key);

    }

 

    /**

     * 判断当前key值 是否存在

     *

     * @param key

     */

    public boolean hasKey(String key) {

        return jedisCluster.exists(key);

    }

 

 

    /**

     * 设置缓存,并且自己指定过期时间

     * @param key

     * @param value

     * @param expireTime 过期时间

     */

    public void setWithExpireTime( String key, String value, int expireTime) {

        jedisCluster.setex(key, expireTime, value);

        LOGGER.debug("RedisUtil:setWithExpireTime cache key={},value={},expireTime={}", key, value, expireTime);

    }

 

 

    /**

     * 获取指定key的缓存

     * @param key

     */

    public String get(String key) {

        String value = jedisCluster.get(key);

        LOGGER.debug("RedisUtil:get cache key={},value={}",key, value);

        return value;

    }

 

    /**

     * 删除指定key的缓存

     * @param key

     */

    public void delete(String key) {

        jedisCluster.del(key);

        LOGGER.debug("RedisUtil:delete cache key={}", key);

    }

 

}

6.帮助类的使用方式

1

2

@Autowired

   private RedisUtil redisUtil;

除了以上

也可以使用如下spring配置

使用jedis连接池

yml配置文件:

复制代码

spring:
  redis:
    password:    # 密码(默认为空)
    timeout: 6000ms  # 连接超时时长(毫秒)
    cluster:
      nodes:
        - 192.168.1.236:7001
        - 192.168.1.236:7002
        - 192.168.1.236:7003
        - 192.168.1.244:7004
        - 192.168.1.244:7005
        - 192.168.1.244:7006 
    jedis:
      pool:
        max-active: 1000  # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1ms      # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 10      # 连接池中的最大空闲连接
        min-idle: 5       # 连接池中的最小空闲连接

复制代码

 

//连接池注入配置信息

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@Configuration

public class RedisConfig {

   @Autowired

   private RedisConnectionFactory factory;

 

   @Bean

    public RedisTemplate<String, Object> redisTemplate() {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setHashValueSerializer(new StringRedisSerializer());

        redisTemplate.setValueSerializer(new StringRedisSerializer());

        redisTemplate.setConnectionFactory(factory);

        return redisTemplate;

    }

}

  

在使用的地方直接注入即可

1

2

@Autowired

private RedisTemplate<String, Object> redisTemplate;

需要引入

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.1.9.RELEASE</version>
</dependency>

 

直接使用spring data redis 中封装的方法进行操作

package com.web.test.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;


@RestController
public class TestController {

    @Resource(name="redisTemplate")
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/redisTest")
    public String redisTest(){
        return redisTemplate.opsForValue().get("username");
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值