SpringBoot 整合Redis同时支持单机和集群模式 - Go语言中文社区

SpringBoot 整合Redis同时支持单机和集群模式


Redis是干啥的,我就不在这说了,我说的肯定很肤浅,不出意外,你们会觉得我说了和没说一样,所以大家还是去找度娘靠谱。

下面分不同情况来设置:(我这里是yml配置,properties和这个类似)

一、单机redis配置

适用于:生产、测试、开发 redis 均为单机

redis:
    # Redis数据库索引(默认为0)
    database: 0
    host: xxx.xxx.xx.xx
    port: 6379
    # Redis服务器连接密码(默认为空)
    password:
    # 连接超时时间(毫秒)
    timeout: 5000ms
    jedis:
      pool:
        #最大连接数据库连接数,设 0 为没有限制
        max-active: 8
        #最大等待连接中的数量,设 0 为没有限制
        max-idle: 8
        #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
        max-wait: -1ms
        #最小等待连接中的数量,设 0 为没有限制
        min-idle: 0
    lettuce:
      pool:
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 8
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池中的最小空闲连接
        min-idle: 0
      shutdown-timeout: 100ms
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;

/**
     * @Author: yansf
     * @Description:redis配置
     * @Date: 3:18 PM 2018/4/18
     * @Modified By:
     */
@Configuration
@ConditionalOnClass(RedisTemplate.class)

public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setDefaultSerializer(new RedisJsonSerializer<>());
        template.afterPropertiesSet();
        //UserUtil.setCache(template);
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}

二、redis集群

适用于:各环境均为redis集群

只需要将单机配置中的host替换成cluster: nodes:如下图:(对就是这么简单

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/Sibylsf/article/details/105820463
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-12 20:40:29
  • 阅读 ( 1520 )
  • 分类:Redis

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢