Springboot2.x整合同時操作多個Redis庫

樑雲亮發表於2020-11-04

原理

直接通過配置注入多個RedisTemplate,需要用到哪個庫時直接使用對應的RedisTemplate即可。

第一步:建立專案指定Maven依賴:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.10.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.10.1</version>
</dependency>
<!--        解決java8新日期API反序列化異常:com.fasterxml.jackson.databind.exc.InvalidDefinitionException-->
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!--redis預設使用的Lettuce客戶端-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--使用預設的Lettuce時,若配置spring.redis.lettuce.pool則必須配置該依賴-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

第二步:application.yml

redis:
    database:
        db1: 5
        db2: 7
    host: 127.0.0.1
    port: 6379
    password: 123456
    timeout: 1000
    pool:
        max-active: 100
        max-idle: 3
        min-idle: 0
        max-wait: -1

第三步:Redis配置檔案

@Configuration
public class RedisConfig {
    @Value("${redis.database.db1}")
    private int db1;

    @Value("${redis.database.db2}")
    private int db2;

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

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

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

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

    @Value("${redis.pool.max-active}")
    private int maxActive;

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

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

    @Value("${redis.pool.max-wait}")
    private int maxWait;

    @Bean
    public GenericObjectPoolConfig getPoolConfig(){
        // 配置redis連線池
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxWaitMillis(maxWait);
        return poolConfig;
    }

    @Bean(name = "redisTemplate1")
    public StringRedisTemplate getRedisTemplate1(){
        return getStringRedisTemplate(db1);
    }

    @Bean(name = "redisTemplate2")
    public StringRedisTemplate getRedisTemplate2(){
        // 構建工廠物件
        return getStringRedisTemplate(db2);
    }

    private StringRedisTemplate getStringRedisTemplate(int database) {
        // 構建工廠物件
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(host);
        config.setPort(port);
        //config.setPassword(RedisPassword.of(password));
        LettucePoolingClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofSeconds(timeout))
                .poolConfig(getPoolConfig())
                .build();
        LettuceConnectionFactory factory = new LettuceConnectionFactory(config, clientConfig);
        // 設定使用的redis資料庫
        factory.setDatabase(database);
        // 重新初始化工廠
        factory.afterPropertiesSet();
        return new StringRedisTemplate(factory);
    }
}

第四步:測試程式碼

@SpringBootTest
public class DemoTest {
    @Resource(name = "redisTemplate1")
    private StringRedisTemplate redisTemplate1;

    @Resource(name = "redisTemplate2")
    private StringRedisTemplate redisTemplate2;

    @Test
    public void fun1() {
        // 向redis中存值
        redisTemplate1.opsForValue().set("name", "zhangsan");
        redisTemplate2.opsForValue().set("name", "lisi");
    }

    @Test
    public void fun2() {
        // 向redis中存值同時指定過期時間
        redisTemplate1.opsForValue().set("name", "zhangsan");
        redisTemplate1.expire("name",3, TimeUnit.MINUTES);
        redisTemplate2.opsForValue().set("name", "lisi");
        redisTemplate2.expire("name",3, TimeUnit.MINUTES);
    }
}

相關文章