spring starter连接redis

博客介绍了自定义spring starter连接redis的方法。配置参数后,使用哨兵集群模式初始化jedisPool,与普通连接有区别。通过jedis客户端连接redis,每次使用时从pool获取,使用后关闭。

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

自定义spring starter连接redis

配置参数

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author tonfu.chia
 * Created by  2019-06-21
 */
@Configuration
@Slf4j
@Data
public class JedisProperties {

    @Value("${bcs.redis.sentinel.master}")
    private String masterName;

    @Value("${bcs.redis.sentinel.nodes}")
    private String nodes;

    @Value("${bcs.redis.timeout}")
    private int timeout;

    @Value("${bcs.redis.pool.max-idle}")
    private int maxIdle;

    @Value("${bcs.redis.pool.max-wait-millis}")
    private long maxWaitMillis;

    @Value("${bcs.redis.pool.max-total}")
    private int maxTotal;

    @Value("${bcs.redis.pool.min-idle}")
    private int minIdle;

    @Value("${bcs.redis.password}")
    private String password;

}

初始化jedisPool,我这里是使用的哨兵集群模式,和普通连接有点区别

	@Bean
    public JedisSentinelPool bcsJedisSentinelPool() {

        String[] nodes = properties.getNodes().split(",");
        Set<String> set = new HashSet<>(Arrays.asList(nodes));
        //        set.add("192.168.9.72:6389");
        //        set.add("192.168.9.73:6390");
        //        set.add("192.168.46.150:6387");
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(properties.getMaxIdle());
        jedisPoolConfig.setMinIdle(properties.getMinIdle());
        jedisPoolConfig.setMaxWaitMillis(properties.getMaxWaitMillis());
        jedisPoolConfig.setMaxTotal(properties.getMaxTotal());
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnReturn(true);
        jedisPoolConfig.setTestWhileIdle(true);
        JedisSentinelPool jedisSentinelPool =
                new JedisSentinelPool(properties.getMasterName(), set, jedisPoolConfig,
                        properties.getTimeout(), properties.getPassword());
        return jedisSentinelPool;
    }

连接redis,使用jedis客户端,每次使用时从pool里获取,使用后close掉。

 	@Autowired
    JedisSentinelPool jedisSentinelPool;
	
	/**
     * 执行
     */
    private void execute() {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            //执行redis命令,业务代码
        } catch (Exception e) {
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

写的比较跳跃,如果有什么需要了解的,可以给我留言,只是记录下工作中的代码片段。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值