美文网首页springbootSpringjava 设计
springBoot配置Redis多数据源+完整测试

springBoot配置Redis多数据源+完整测试

作者: 宇宙小神特别萌 | 来源:发表于2019-08-27 14:15 被阅读0次
    springboot配置redis多数据源目录.png

    前言:
    项目:springboot2.0.5 + redis + swagger2
    测试目的:配置redis多数据源
    配置数据源个数: 这里配置了双数据源,可以复制配置多数据源。

    这里的测试,可以直接拿到项目中使用,可以无脑复制及使用!

    1、配置依赖 pom.xml

    <dependencies>
       <!--redis依赖-->
       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
          <version>2.0.5.RELEASE</version>
       </dependency>
       <dependency>
          <groupId>redis.clients</groupId>
          <artifactId>jedis</artifactId>
          <version>2.9.0</version>
       </dependency>
    
       <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
           <version>1.16.18</version>
          <optional>true</optional>
       </dependency>
    
       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
          <version>2.0.5.RELEASE</version>
       </dependency>
       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-tomcat</artifactId>
          <version>2.0.5.RELEASE</version>
          <scope>provided</scope>
       </dependency>
       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <version>2.0.5.RELEASE</version>
          <scope>test</scope>
       </dependency>
    
       <!--集成swagger-API-->
       <dependency>
          <groupId>io.swagger</groupId>
          <artifactId>swagger-models</artifactId>
          <version>1.5.21</version>
          <scope>compile</scope>
       </dependency>
       <dependency>
          <groupId>io.swagger</groupId>
          <artifactId>swagger-annotations</artifactId>
          <version>1.5.21</version>
          <scope>compile</scope>
       </dependency>
       <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger-ui</artifactId>
          <version>2.9.2</version>
       </dependency>
       <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger2</artifactId>
          <version>2.9.2</version>
          <exclusions>
             <exclusion>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-models</artifactId>
             </exclusion>
             <exclusion>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-annotations</artifactId>
             </exclusion>
          </exclusions>
       </dependency>
       </dependencies>
    
    

    2、redis配置 application.yml

    # 主配置文件主要用来存放公共设置,不受环境配置影响
    server:
      port: 8080
      servlet:
        context-path: /springboot-test-redis2
    spring:
      redis:
        database: 6   # Redis数据库索引(默认为0)
        host: 127.0.0.1  # Redis服务器地址
        port: 6379         # Redis服务器连接端口
        password:    # Redis服务器连接密码(默认为空)
        max-wait: 30000    # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-active: 100   # 连接池最大连接数(使用负值表示没有限制)
        max-idle: 20     # 连接池中的最大空闲连接
        min-idle: 0     # 连接池中的最小空闲连接
        timeout: 5000  # 连接超时时间(毫秒)
      #自定义配置
      redis2:
        database: 5   # Redis数据库索引(默认为0)
        host: 192.168.2.169  # Redis服务器地址,若测试也可以用127.0.0.1本地的redis,因为database索引库用的不是一个
        port: 6379         # Redis服务器连接端口
        password:    # Redis服务器连接密码(默认为空)
        timeout: 5000  # 连接超时时间(毫秒)
        
    

    3、在config文件下配置redis多实例

    RedisConfig.ava

    package com.dist.config;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.connection.RedisPassword;
    import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
    import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
    import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    import org.springframework.util.ObjectUtils;
    
    import java.time.Duration;
    
    /**设置Redis多实例的基类
     * @author zhengja@dist.com.cn
     * @data 2019/7/29 10:17
     */
    @EnableCaching
    @Configuration
    public class RedisConfig extends CachingConfigurerSupport{
    
        /**
         * 数据源1 默认配置(127.0.0.1) redis template
         *
         * @param redisConnectionFactory
         * @return
         */
        @Bean
        public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
            return createRedisTemplate(redisConnectionFactory);
        }
    
        /**
         * 数据源2 redis template
         */
        @Bean
        public RedisTemplate redisTemplate2(
                @Value("${spring.redis2.database}") int database,
                @Value("${spring.redis.timeout}") long timeout,
                @Value("${spring.redis.max-active}") int maxActive,
                @Value("${spring.redis.max-wait}") int maxWait,
                @Value("${spring.redis.max-idle}") int maxIdle,
                @Value("${spring.redis.min-idle}") int minIdle,
    
                @Value("${spring.redis2.host}") String hostName,
                @Value("${spring.redis2.port}") int port,
                @Value("${spring.redis2.password}") String password) {
    
            /* ========= 基本配置 ========= */
            RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
            configuration.setHostName(hostName);
            configuration.setPort(port);
            configuration.setDatabase(database);
            if (!ObjectUtils.isEmpty(password)) {
                RedisPassword redisPassword = RedisPassword.of(password);
                configuration.setPassword(redisPassword);
            }
    
            /* ========= 连接池通用配置 ========= */
            GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
            genericObjectPoolConfig.setMaxTotal(maxActive);
            genericObjectPoolConfig.setMinIdle(minIdle);
            genericObjectPoolConfig.setMaxIdle(maxIdle);
            genericObjectPoolConfig.setMaxWaitMillis(maxWait);
    
            /* ========= jedis pool ========= */
            /*
            JedisClientConfiguration.DefaultJedisClientConfigurationBuilder builder = (JedisClientConfiguration.DefaultJedisClientConfigurationBuilder) JedisClientConfiguration
                    .builder();
            builder.connectTimeout(Duration.ofSeconds(timeout));
            builder.usePooling();
            builder.poolConfig(genericObjectPoolConfig);
            JedisConnectionFactory connectionFactory = new JedisConnectionFactory(configuration, builder.build());
            // 连接池初始化
            connectionFactory.afterPropertiesSet();
            */
    
            /* ========= lettuce pool ========= */
            LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
            builder.poolConfig(genericObjectPoolConfig);
            builder.commandTimeout(Duration.ofSeconds(timeout));
            LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(configuration, builder.build());
            connectionFactory.afterPropertiesSet();
    
            /* ========= 创建 template ========= */
            return createRedisTemplate(connectionFactory);
        }
    
        /**
         * json 实现 redisTemplate
         * <p>
         * 该方法不能加 @Bean 否则不管如何调用,connectionFactory都会是默认配置
         *
         * @param redisConnectionFactory
         * @return
         */
        public RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
    
            Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    
            redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.afterPropertiesSet();
            return redisTemplate;
        }
    
    /*
    Redis 连接池: Lettuce、Jedis 比较
    
    Jedis:
    Jedis在实现上是直接连接的redis server,如果在多线程环境下是非线程安全的,这个时候只有使用连接池,为每个Jedis实例增加物理连接
    
    Lettuce:
    Lettuce的连接是基于Netty的,连接实例(StatefulRedisConnection)可以在多个线程间并发访问,应为StatefulRedisConnection是线程安全的,所以一个连接实例(StatefulRedisConnection)就可以满足多线程环境下的并发访问,当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。
    lettuce主要利用netty实现与redis的同步和异步通信。
     */
    }
    
    

    4、配置Swagger2Config

    用于测试接口,好调试。

    package com.dist.config;
    
    import com.google.common.base.Predicate;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    /**
     * @author yangmin
     * @date 2018/8/15
     * @desc
     */
    @Configuration
    @EnableSwagger2
    public class Swagger2Config {
        @Bean
        public Docket adminApi(){
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("Admin API")
                    .forCodeGeneration(true)
                    .pathMapping("/")
                    .select()
                    .paths(paths())
                    .build()
                    .apiInfo(apiInfo())
                    .useDefaultResponseMessages(false);
        }
    
        private Predicate<String> paths(){
            return PathSelectors.regex("^/(?!error).*$");
        }
    
        private ApiInfo apiInfo(){
            Contact contact = new Contact("BaiDu", "controller://baidu.com", " zhengja@dist.com.cn");
            return new ApiInfoBuilder()
                    .title("个人SpringBoot测试系统")
                    .description("开发API文档")
                    .contact(contact)
                    .version("1.0")
                    .build();
        }
    }
    
    

    5、配置Redis的工具类

    这里要配置两份,每份对应不同的数据源。

    1.数据源一对应的工具类:RedisUtil-redisTemplate
    package com.dist.util;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    
    /**
     * 默认 redisTemplate封装
     * @author zhengja@dist.com.cn
     * @data 2019/7/29 10:17
     */
    @Component
    public class RedisUtil {
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
            this.redisTemplate = redisTemplate;
        }
    
        /**
         * 普通缓存获取
         * @param key 键
         * @return 值
         */
        public Object get(String key){
            return key==null?null:redisTemplate.opsForValue().get(key);
        }
    
        /**
         * 普通缓存放入
         * @param key 键
         * @param value 值
         * @return true成功 false失败
         */
        public boolean set(String key,Object value) {
            try {
                redisTemplate.opsForValue().set(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    }
    
    
    2.数据源一对应的工具类:RedisUtil2-redisTemplate2
    package com.dist.util;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    
    /**
     * 数据源2 redisTemplate2封装
     * @author zhengja@dist.com.cn
     * @data 2019/7/29 10:17
     */
    @Component
    public class RedisUtil2 {
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate2;
    
        public RedisUtil2(RedisTemplate<String, Object> redisTemplate2) {
            this.redisTemplate2 = redisTemplate2;
        }
    
        /**
         * 普通缓存获取
         * @param key 键
         * @return 值
         */
        public Object get(String key){
            return key==null?null:redisTemplate2.opsForValue().get(key);
        }
    
        /**
         * 普通缓存放入
         * @param key 键
         * @param value 值
         * @return true成功 false失败
         */
        public boolean set(String key,Object value) {
            try {
                redisTemplate2.opsForValue().set(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    }
    
    

    6、测试Redis配置的双数据源

    Controller.java 接口层

    package com.dist.controller;
    
    import com.dist.util.RedisUtil;
    import com.dist.util.RedisUtil2;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiParam;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author zhengja@dist.com.cn
     * @data 2019/7/29 10:41
     */
    @Api(tags = {"RedisController"},description = "redis双数据源测试")
    @RequestMapping(value = "rest/redis")
    @RestController
    @Slf4j
    public class RedisController {
    
        /**
         * 封装的工具类:默认 127.0.0.1
         */
        @Autowired
        RedisUtil redisUtil;
    
        /**
         * 封装的工具类2:192.168.2.169
         */
        @Autowired
        RedisUtil2 redisUtil2;
    
        @ApiOperation(value = "redis数据源1",httpMethod = "GET")
        @RequestMapping(value = "v1/redis1",method = RequestMethod.GET)
        public Object redis1(@ApiParam(value = "reids key值") @RequestParam String key,
                             @ApiParam(value = "redis value值") @RequestParam String value){
            boolean set = redisUtil.set(key, value);
            log.info("保存结果:"+set);
            if (set){
                return redisUtil.get(key);
            }
            return null;
        }
    
        @ApiOperation(value = "redis数据源2",httpMethod = "GET")
        @RequestMapping(value = "v2/redis2",method = RequestMethod.GET)
        public Object redis2(@ApiParam(value = "reids key值") @RequestParam String key,
                             @ApiParam(value = "redis value值") @RequestParam String value){
            boolean set = redisUtil2.set(key, value);
            log.info("保存结果:"+set);
            if (set){
                return redisUtil2.get(key);
            }
            return null;
        }
    
    }
    
    

    7、启动swagger页面测试

    1.在resources/static下创建index.html,内容如下:

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>springboot-test-redis2</title>
    </head>
    <body>
    <h1>首页面</h1>
    
    <h2>springboot-test-redis2</h2>
    
    <a href="http://localhost:8080/springboot-test-redis2/swagger-ui.html">进入swagger页面测试</a>
    </body>
    </html>
    

    这个项目地址改成自己的项目访问地址:http://localhost:8080/springboot-test-redis2

    2.访问index.html页面:
    index页面.png
    3.点击进入swagger页面测试
    swagger页面.png
    4.测试这两个数据源存数据和取数据
    数据源1-测试:
    数据源1.png 数据源1-结果.png
    数据源2-测试:
    数据源2.png 数据源2-结果.png
    双数据源配置、测试成功!
    双数据源还不满足你的业务要求,可以在RedisConfig继续新增数据源配置!

    相关文章

      网友评论

        本文标题:springBoot配置Redis多数据源+完整测试

        本文链接:https://www.haomeiwen.com/subject/huleectx.html