spring boot整合redis多实例

最近项目中遇到需要连接两个redis实例的情况,于是就在spring boot原先的基础上修改了一点。

1. 定义配置文件的bean,继承自RedisProperties

  • 下面是配置文件的内容
redis:
  config:
    multiple:
    - name: develop
      database: 0
      lettuce:
        pool:
          max-idle: 10
          max-active: 1000
          max-wait: 1000ms
          min-idle: 5
      timeout: 100000ms
      cluster:
        nodes: 192.168.2.86:6380,192.168.2.87:6380,192.168.2.88:6380
    - name: test
      database: 0
      lettuce:
        pool:
          max-idle: 10
          max-active: 1000
          max-wait: 1000ms
          min-idle: 5
      timeout: 100000ms
      cluster:
        nodes: 192.168.2.86:6379,192.168.2.87:6379,192.168.2.88:6379
  • 配置文件对应的实体
@Data
public class MultipleRedisProperties extends RedisProperties {

    /**
     * redis的自定义名称
     */
    private String name;

}

2. 获取配置文件属性的值

@Getter
@Setter
@ConfigurationProperties(prefix = "redis.config")
public class RedisConfigPropertySupport {

    List<MultipleRedisProperties> multiple = new ArrayList<>();

}

3.加载到spring 容器中

@Getter
@Setter
@Configuration
@EnableConfigurationProperties(RedisConfigPropertySupport.class)
public class RedisPropertiesAutoConfig {

    private RedisConfigPropertySupport redisProperties;

    public RedisPropertiesAutoConfig(RedisConfigPropertySupport redisProperties) {
        this.redisProperties = redisProperties;
    }
}
  • 创建redis部署模式的枚举值
public enum RedisModeEnum {

    /**
     * 单机
     */
    STAND_ALONE,

    /**
     * 哨兵
     */
    SENTINEL,

    /**
     * 集群
     */
    CLUSTER

}

4. 使用spring boot的创建连接工厂进行配置redis的连接工厂类

public abstract class AbstractRedisConnectionFactoryConfig implements BeanFactoryAware, InitializingBean {

    @Autowired
    private RedisPropertiesAutoConfig redisProperties;

    private BeanFactory beanFactory;

    private static final String DEFAULT = "default";

    @Override
    public void afterPropertiesSet() {
        ConfigurableListableBeanFactory listableBeanFactory = (ConfigurableListableBeanFactory) this.getBeanFactory();
        if (getRedisProperties().getRedisProperties() == null || CollectionUtils.isEmpty(getRedisProperties().getRedisProperties().getMultiple())) {
            RedisConnectionFactory defaultConnectionFactory = buildRedisConnectionFactory(null);
            listableBeanFactory.registerSingleton(DEFAULT + "_redisConnectionFactory", defaultConnectionFactory);
        }
        getRedisProperties().getRedisProperties().getMultiple().forEach(redisProperty -> {
            RedisConnectionFactory redisConnectionFactory = buildRedisConnectionFactory(redisProperty);
            listableBeanFactory.registerSingleton(redisProperty.getName().trim() + "_redisConnectionFactory", redisConnectionFactory);
        });
    }

    /**
     * 创建{@link RedisConnectionFactory},由子类实现
     *
     * @param redisProperties
     * @return
     */
    protected abstract RedisConnectionFactory buildRedisConnectionFactory(RedisProperties redisProperties);

    /**
     * 根据redisProperty判断redis部署模式
     *
     * @param redisProperty redisProperty
     * @return {@link RedisModeEnum}
     */
    protected abstract RedisModeEnum getRedisMode(RedisProperties redisProperty);

    static class RedisConnectionPoolBuilderFactory {

        public LettuceClientConfiguration.LettuceClientConfigurationBuilder createBuilder(RedisProperties.Pool properties) {
            return LettucePoolingClientConfiguration.builder().poolConfig(getPoolConfig(properties));
        }

        private GenericObjectPoolConfig<?> getPoolConfig(RedisProperties.Pool properties) {
            GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
            config.setMaxTotal(properties.getMaxActive());
            config.setMaxIdle(properties.getMaxIdle());
            config.setMinIdle(properties.getMinIdle());
            if (properties.getTimeBetweenEvictionRuns() != null) {
                config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns().toMillis());
            }
            if (properties.getMaxWait() != null) {
                config.setMaxWaitMillis(properties.getMaxWait().toMillis());
            }
            return config;
        }
    }

    @Override
    public void setBeanFactory(@Nullable BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public BeanFactory getBeanFactory() {
        return beanFactory;
    }

    public RedisPropertiesAutoConfig getRedisProperties() {
        return redisProperties;
    }
}
  • 工厂实现类
@Configuration
public class LettuceRedisConnectionFactoryConfig extends AbstractRedisConnectionFactoryConfig {

    @Override
    protected RedisConnectionFactory buildRedisConnectionFactory(RedisProperties redisProperty) {
        if (redisProperty == null) {
            //创建默认的redis连接工厂
            LettuceConnectionFactory defaultConnectionFactory = createDefaultConnectionFactory();

            defaultConnectionFactory.afterPropertiesSet();
            return defaultConnectionFactory;
        }
        LettuceClientConfiguration clientConfig = buildLettuceClientConfiguration(DefaultClientResources.create(),
                redisProperty.getLettuce().getPool(), redisProperty);
        //创建lettuce连接工厂
        LettuceConnectionFactory redisConnectionFactory;
        if (getRedisMode(redisProperty) == RedisModeEnum.CLUSTER) {
            redisConnectionFactory = new LettuceConnectionFactory(new RedisClusterConfiguration
                    (redisProperty.getCluster().getNodes()), clientConfig);
        } else if (getRedisMode(redisProperty) == RedisModeEnum.SENTINEL) {
            redisConnectionFactory = new LettuceConnectionFactory(new RedisSentinelConfiguration
                    (redisProperty.getSentinel().getMaster(), new HashSet<>(redisProperty.getSentinel().getNodes())), clientConfig);
        } else {
            redisConnectionFactory = new LettuceConnectionFactory(new RedisStandaloneConfiguration
                    (redisProperty.getHost(), redisProperty.getPort()), clientConfig);
        }

        redisConnectionFactory.afterPropertiesSet();
        return redisConnectionFactory;
    }

    @Override
    protected RedisModeEnum getRedisMode(RedisProperties redisProperty) {
        if (redisProperty.getCluster() != null) {
            Assert.notNull(redisProperty.getCluster().getNodes(), "集群节点不能为空");
            return RedisModeEnum.CLUSTER;
        } else if (redisProperty.getSentinel() != null) {
            Assert.hasText(redisProperty.getSentinel().getMaster(), "哨兵的主节点不能为空");
            Assert.notNull(redisProperty.getSentinel().getNodes(), "哨兵的从节点不能为空");
            return RedisModeEnum.SENTINEL;
        }
        return RedisModeEnum.STAND_ALONE;
    }

    private LettuceClientConfiguration buildLettuceClientConfiguration(ClientResources clientResources, RedisProperties.Pool pool, RedisProperties redisProperties) {
        LettuceClientConfiguration.LettuceClientConfigurationBuilder builder = createBuilder(pool);
        applyProperties(builder, redisProperties);
        builder.clientResources(clientResources);
        return builder.build();
    }

    private LettuceClientConfiguration.LettuceClientConfigurationBuilder applyProperties(
            LettuceClientConfiguration.LettuceClientConfigurationBuilder builder, RedisProperties redisProperties) {
        if (redisProperties.isSsl()) {
            builder.useSsl();
        }
        if (redisProperties.getTimeout() != null) {
            builder.commandTimeout(redisProperties.getTimeout());
        }
        if (redisProperties.getLettuce() != null) {
            RedisProperties.Lettuce lettuce = redisProperties.getLettuce();
            if (lettuce.getShutdownTimeout() != null && !lettuce.getShutdownTimeout().isZero()) {
                builder.shutdownTimeout(redisProperties.getLettuce().getShutdownTimeout());
            }
        }
        return builder;
    }

    private LettuceClientConfiguration.LettuceClientConfigurationBuilder createBuilder(RedisProperties.Pool pool) {
        if (pool == null) {
            return LettuceClientConfiguration.builder();
        }
        return new RedisConnectionPoolBuilderFactory().createBuilder(pool);
    }

    private LettuceConnectionFactory createDefaultConnectionFactory() {
        return new LettuceConnectionFactory(new RedisStandaloneConfiguration());
    }
}

5.redisTemplate的配置

public abstract class AbstractRedisConfiguration implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    protected RedisTemplate<String, Object> buildRedisTemplate(String name) {
        return buildRedisTemplate(name, new GenericJackson2JsonRedisSerializer(), false);
    }

    protected RedisTemplate<String, Object> buildRedisTemplate(String name, Boolean enableTransaction) {
        return buildRedisTemplate(name, new GenericJackson2JsonRedisSerializer(), enableTransaction);
    }

    protected RedisTemplate<String, Object> buildRedisTemplate(String name, RedisSerializer redisSerializer,
                                                               Boolean enableTransaction) {
        if (StringUtils.isBlank(name)) {
            throw new IllegalArgumentException("redis properties name field must not null");
        }
        RedisConnectionFactory redisConnectionFactory = getRedisConnectionFactory(name);
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(redisSerializer);
        redisTemplate.setHashValueSerializer(redisSerializer);
        redisTemplate.setEnableTransactionSupport(enableTransaction);
        return redisTemplate;
    }

    private RedisConnectionFactory getRedisConnectionFactory(String name) {
        return (RedisConnectionFactory) applicationContext.getBean(name.trim() + "_redisConnectionFactory");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
  • 配置redisTemplate
@Configuration
@DependsOn("lettuceRedisConnectionFactoryConfig")
public class RedisConfiguration extends AbstractRedisConfiguration {

    @Bean("developRedisTemplate")
    public RedisTemplate<String, Object> getDevelopRedisTemplate() {
        return buildRedisTemplate("develop");
    }

    @Bean("testRedisTemplate")
    public RedisTemplate<String, Object> getTestRedisTemplate() {
        return buildRedisTemplate("test");
    }
}
  • 下面利用spring boot的ApplicationRunner接口测试一下,用redis客户端查看发现结果已经存入进去了。
     @Autowired
    @Qualifier("developRedisTemplate")
    private RedisTemplate developRedisTemplate;

    @Autowired
    @Qualifier("testRedisTemplate")
    private RedisTemplate testRedisTemplate;

   @Override
    public void run(ApplicationArguments args) throws Exception {
        developRedisTemplate.opsForValue().set("develop_RedisMultiple", "test", 120, TimeUnit.SECONDS);
        testRedisTemplate.opsForValue().set("test_RedisMultiple", "test", 120, TimeUnit.SECONDS);
    }

原文地址:https://www.cnblogs.com/wenwblog/p/11784166.html

时间: 2024-11-07 05:29:19

spring boot整合redis多实例的相关文章

Spring Boot整合Redis

一.Spring Boot对Redis的支持 Spring对Redis的支持是使用Spring Data Redis来实现的,一般使用Jedis或者lettuce(默认),Java客户端在 org.springframework.boot.autoconfigure.data.redis(Spring Boot 2.x) 中redis的自动配置 AutoConfigureDataRedis RedisAutoConfiguration提供了RedisTemplate与StringRedisTem

Spring Boot 整合Redis 实现缓存

本文提纲 一.缓存的应用场景 二.更新缓存的策略 三.运行 springboot-mybatis-redis 工程案例 四.springboot-mybatis-redis 工程代码配置详解 运行环境: Mac OS 10.12.x JDK 8 + Redis 3.2.8 Spring Boot 1.5.1.RELEASE 一.缓存的应用场景 什么是缓存? 在互联网场景下,尤其 2C 端大流量场景下,需要将一些经常展现和不会频繁变更的数据,存放在存取速率更快的地方.缓存就是一个存储器,在技术选型

spring boot 整合 redis

自己开发环境需要安装 redis 服务,百度一下很多,下面主要说明Springboot 集成 redis 讲解 我的版本 java8 + redis3.0 + springboot 1.5.9. Spring redis 集成了 jedis redis 中存储的是 bytes 1 spring boot已经支持集成 redis,在 mvn 中只需添加依赖即可.pom 配置片段如下 <parent> <groupId>org.springframework.boot</grou

Spring Boot集成redis完整实例

添加依赖: (Spring Data Redis) 启动redis: 配置文件中进行配置: redis基本使用思路: redis中不存在就查询数据库然后存入redis: 查看日志: 原文地址:https://www.cnblogs.com/niwotaxuexiba/p/10850025.html

Spring boot 整合redis单机版

   一.安装redis 这个不多说,网上有各种系统安装redis的操作, redis安装 二.创建sprigboot项目 这个也不多说,不会的前面有相关教程. 三.添加maven坐标 四.编写springboot配置文件 五.可以操作redis了 我把缓存存在redis 相关代码如下: 5.1目录结构 5.2 模拟数据 5.3缓存 5.4开启缓存 5.5测试接口 六.当第一次访问的时候打印 第二次直接从redis中获得数据 如果有什么问题,可以一起探讨欢迎加我qq1058179540 原文地址

Spring Boot 整合 Lettuce Redis

SpringBoot?是为了简化?Spring?应用的创建.运行.调试.部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程 Spring Boot?除了支持常见的ORM框架外,更是对常用的中间件提供了非常好封装,随着Spring Boot2.x的到来,支持的组件越来越丰富,也越来越成熟,其中对Redis的支持不仅仅是丰富了它的API,更是替换掉底层Jedis的依赖,取而代之换成了Le

spring boot 整合 quartz 集群环境 实现 动态定时任务配置【原】

最近做了一个spring boot 整合 quartz  实现 动态定时任务配置,在集群环境下运行的 任务.能够对定时任务,动态的进行增删改查,界面效果图如下: 1. 在项目中引入jar 2. 将需要的表导入数据库 官网上有不同数据库的脚本,找到对应的,导入即可 3. java 代码 将quartz 的相关配置文件,配置为暴露bean,方便后期引用. 有一处关键的地方,就是注入spring 上下文,也可以算是一个坑.如果,不注入spring 上下文,那么新添加的定时任务job,是新new 的一个

Spring Boot使用redis实现数据缓存

基于Spring Boot 1.5.2.RELEASE版本,一方面验证与Redis的集成方法,另外了解使用方法. 集成方法 配置依赖 修改pom.xml,增加如下内容. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 配置Redis

Spring boot、Redis、ActiveMQ、Nginx、Mycat、Netty、Jvm大型分布式项目实战视频教程

15套java架构师.集群.高可用.高可扩展.高性能.高并发.性能优化.Spring boot.Redis.ActiveMQ.Nginx.Mycat.Netty.Jvm大型分布式项目实战视频教程 视频课程内容包含: 高级Java架构师包含:Spring boot.Spring  cloud.Dubbo.Redis.ActiveMQ.Nginx.Mycat.Spring.MongoDB.ZeroMQ.Git.Nosql.Jvm.Mecached.Netty.Nio.Mina.性能调优.高并发.to