Springboot2.0集成Redis(StringRedisTemplate)多数据源


1、Maven依赖

maven依赖


2、application.yml配置redis

spring:

  # redis 相关

  redis:

    database: 0  # Redis数据库索引(默认为0)

    host: 127.0.0.1  # Redis服务器地址

    port: 6379  # Redis服务器连接端口

    password:    # Redis服务器连接密码(默认为空)

    timeout: 8000  # 连接超时时间(毫秒)

    lettuce:

      pool:

        max-active: 8

        max-idle: 8

        max-wait: -1

        min-idle: 0

  db-redis:

    host: 127.0.0.1

    port: 6380

    database: 0

    password:

    lettuce:

      pool:

        max-active: 16

        max-wait: 100

        max-idle: 8

        min-idle: 4

  cache-redis:

    host: 127.0.0.1

    port: 6379

    database: 0

    password:

    lettuce:

      pool:

        max-active: 16

        max-wait: 100

        max-idle: 8

        min-idle: 4

3、RedisTemplateConfig配置

@EnableCaching

@Configuration

public class RedisTemplateConfig {

@Primary

    @Bean(name ="dbLettuceConnectionFactory")

@ConditionalOnBean(name ="dbRedisConfig")

public LettuceConnectionFactorydbLettuceConnectionFactory(RedisStandaloneConfiguration dbRedisConfig, GenericObjectPoolConfig dbPoolConfig) {

LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder().commandTimeout(Duration.ofMillis(5000)).poolConfig(dbPoolConfig).build();

        return new LettuceConnectionFactory(dbRedisConfig, clientConfig);

    }

@Primary

    @Bean(name ="dbRedisTemplate")

@ConditionalOnBean(name ="dbLettuceConnectionFactory")

public StringRedisTemplatedbRedisTemplate(@Qualifier("dbLettuceConnectionFactory")  LettuceConnectionFactory dbLettuceConnectionFactory) {

StringRedisTemplate redisTemplate =new StringRedisTemplate();

        StringRedisSerializer stringRedisSerializer =new StringRedisSerializer();

        redisTemplate.setKeySerializer(stringRedisSerializer);

        redisTemplate.setValueSerializer(stringRedisSerializer);

        redisTemplate.setConnectionFactory(dbLettuceConnectionFactory);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;

    }

@Configuration

    @ConditionalOnProperty(name ="host", prefix ="spring.db-redis")

public static class DbRedisConfig {

@Value("${spring.db-redis.host:127.0.0.1}")

private Stringhost;

        @Value("${spring.db-redis.port:6379}")

private Integerport;

        @Value("${spring.db-redis.password:}")

private Stringpassword;

        @Value("${spring.db-redis.database:0}")

private Integerdatabase;

        @Value("${spring.db-redis.lettuce.pool.max-active:8}")

private IntegermaxActive;

        @Value("${spring.db-redis.lettuce.pool.max-idle:8}")

private IntegermaxIdle;

        @Value("${spring.db-redis.lettuce.pool.max-wait:-1}")

private LongmaxWait;

        @Value("${spring.db-redis.lettuce.pool.min-idle:0}")

private IntegerminIdle;

        @Bean

        public GenericObjectPoolConfigdbPoolConfig() {

GenericObjectPoolConfig config =new GenericObjectPoolConfig();

            config.setMaxTotal(maxActive);

            config.setMaxIdle(maxIdle);

            config.setMinIdle(minIdle);

            config.setMaxWaitMillis(maxWait);

            return config;

        }

@Bean(name ="dbRedisConfig")

public RedisStandaloneConfigurationdbRedisConfig() {

RedisStandaloneConfiguration config =new RedisStandaloneConfiguration();

            config.setHostName(host);

            config.setPassword(RedisPassword.of(password));

            config.setPort(port);

            config.setDatabase(database);

            return config;

        }

}

@Bean(name ="cacheLettuceConnectionFactory")

@ConditionalOnBean(name ="cacheRedisConfig")

public LettuceConnectionFactorycacheLettuceConnectionFactory(RedisStandaloneConfiguration cacheRedisConfig, GenericObjectPoolConfig cachePoolConfig) {

LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder().commandTimeout(Duration.ofMillis(5000)).poolConfig(cachePoolConfig).build();

        return new LettuceConnectionFactory(cacheRedisConfig, clientConfig);

    }

@Bean(name ="cacheRedisTemplate")

@ConditionalOnBean(name ="cacheLettuceConnectionFactory")

public StringRedisTemplatecacheRedisTemplate(@Qualifier("cacheLettuceConnectionFactory") LettuceConnectionFactory cacheLettuceConnectionFactory) {

StringRedisTemplate redisTemplate =new StringRedisTemplate();

        StringRedisSerializer stringRedisSerializer =new StringRedisSerializer();

        redisTemplate.setKeySerializer(stringRedisSerializer);

        redisTemplate.setValueSerializer(stringRedisSerializer);

        redisTemplate.setConnectionFactory(cacheLettuceConnectionFactory);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;

    }

@Configuration

    @ConditionalOnProperty(name ="host", prefix ="spring.cache-redis")

public static class CacheRedisConfig {

@Value("${spring.cache-redis.host:127.0.0.1}")

private Stringhost;

        @Value("${spring.cache-redis.port:6379}")

private Integerport;

        @Value("${spring.cache-redis.password:}")

private Stringpassword;

        @Value("${spring.cache-redis.database:0}")

private Integerdatabase;

        @Value("${spring.cache-redis.lettuce.pool.max-active:8}")

private IntegermaxActive;

        @Value("${spring.cache-redis.lettuce.pool.max-idle:8}")

private IntegermaxIdle;

        @Value("${spring.cache-redis.lettuce.pool.max-wait:-1}")

private LongmaxWait;

        @Value("${spring.cache-redis.lettuce.pool.min-idle:0}")

private IntegerminIdle;

        @Bean

        public GenericObjectPoolConfigcachePoolConfig() {

GenericObjectPoolConfig config =new GenericObjectPoolConfig();

            config.setMaxTotal(maxActive);

            config.setMaxIdle(maxIdle);

            config.setMinIdle(minIdle);

            config.setMaxWaitMillis(maxWait);

            return config;

        }

@Bean(name ="cacheRedisConfig")

public RedisStandaloneConfigurationcacheRedisConfig() {

RedisStandaloneConfiguration config =new RedisStandaloneConfiguration();

            config.setHostName(host);

            config.setPassword(RedisPassword.of(password));

            config.setPort(port);

            config.setDatabase(database);

            return config;

        }

}

}

4、创建RedisBDUtil和RedisCacheUtil(我用了两个redis源分别作为持久数据库和缓存库),分别注入声明的dbRedisTemplate和cacheRedisTemplate

RedisUtils操作太多了只截取了部分,主要展示通过@Qualifier注入了不同的RedisTemplate

@Component

public class RedisDBUtils {

@Autowired

@Qualifier("dbRedisTemplate")

private StringRedisTemplatedbRedisTemplate;

    /**  默认过期时长,单位:秒 */

    public final static long DEFAULT_EXPIRE =60 *60 *24 *10;

    /**  不设置过期时长 */

    public final static long NOT_EXPIRE = -1;

    /** -------------------key相关操作--------------------- */

/**

* 删除key

*

    * @param key

    */

    public void delete(String key) {

dbRedisTemplate.delete(key);

    }

}

@Component

public class RedisCacheUtils {

@Autowired

@Qualifier("cacheRedisTemplate")

private StringRedisTemplatecacheRedisTemplate;

    /** -------------------key相关操作--------------------- */

/**

* 删除key

*

    * @param key

    */

    public void delete(String key) {

cacheRedisTemplate.delete(key);

    }

/**

* 批量删除key

*

    * @param keys

    */

    public void delete(Collection keys) {

cacheRedisTemplate.delete(keys);

    }

}

5、Controller中的使用

  根据个人需要各自注入,然后就可以分别操作不同的redis库了

@Autowired
private RedisDBUtils redisDBUtils;
@Autowired
private RedisCacheUtils redisCacheUtils;

你可能感兴趣的:(Springboot2.0集成Redis(StringRedisTemplate)多数据源)