欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot如何配置多個(gè)Redis數(shù)據(jù)源(非集群)

 更新時(shí)間:2025年03月13日 09:32:02   作者:程序員阿斌  
這篇文章主要介紹了Springboot如何配置多個(gè)Redis數(shù)據(jù)源(非集群)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

背景

最近線上碰到一個(gè)多redis源的場(chǎng)景,一個(gè)工程需要整合兩個(gè)redis。

這時(shí)使用一些數(shù)據(jù)傳輸、轉(zhuǎn)換工具,例如filebeat、logstash、kafka-connect等,這或許也是個(gè)不錯(cuò)的方法,但是因?yàn)闅v史原因,最后還是需要到工程里面自己整合。話不多說直接開整!

引入依賴

下面直接給出pom文件依賴配置:

        <!-- springboot官方整合redis依賴, 版本根據(jù)自己常用springboot的版本來 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.3.2.RELEASE</version>
        </dependency>
        
        <!-- fastjson依賴 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.32</version>
        </dependency>
        
        <!-- 對(duì)象轉(zhuǎn)換工具 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

添加Redis環(huán)境

application.yml添加redis配置:

spring:
  # redis-1
  redis:
    database: 0
    # redis服務(wù)器地址
    host: 192.168.2.3
    # Redis服務(wù)器連接端口
    port: 6379
    lettuce:
      pool:
        # 連接池最大連接數(shù)(使用負(fù)值表示沒有限制) 默認(rèn) 8
        max-active: 8
        # 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒有限制) 默認(rèn) -1
        max-wait: -1
        # 連接池中的最大空閑連接 默認(rèn) 8
        max-idle: 8
        # 連接池中的最小空閑連接 默認(rèn) 0
        min-idle: 0
    # redis服務(wù)器連接密碼(默認(rèn)為空)
    password: 123456
    timeout: 800
  # redis-2
  redis-live:
    database: 0
    host: 192.168.2.8
    port: 6379
    lettuce:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    password: 234567
    timeout: 800

Redis配置

接下來編寫redis配置類,在裝配不同的RedisTemplate的時(shí)候根據(jù)需要采用不同的序列化方式,在使用的時(shí)候按需引入,下面是我的注入配置:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class RedisTemplateConfig {

    /**
     * live數(shù)據(jù)源
     */
    @Value("${spring.redis-live.host}")
    private String redisLiveHost;

    @Value("${spring.redis-live.port}")
    private int redisLivePort;

    @Value("${spring.redis-live.password}")
    private String redisLivePass;

    @Value("${spring.redis-live.database}")
    private int redisLiveDb;


    /**
     * 公共配置
     */
    @Value("${spring.redis.timeout}")
    private long timeout;

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

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

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

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

    /**
     * 裝配 RedisTemplate
     */
//    @Bean(name = "redisTemplate")
//    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
//        return createRedisTemplate(redisConnectionFactory);
//    }

    @Bean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }


    /**
     * 裝配 StringRedisTemplate
     */
    @Bean(name = "stringRedisTemplate")
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        return createStringRedisTemplate(redisConnectionFactory);
    }

    /**
     * 裝配 live數(shù)據(jù)源
     */
    @Bean(name = "liveStringRedisTemplate")
    public StringRedisTemplate liveStringRedisTemplate() {
        return createStringRedisTemplate(redisLiveHost, redisLivePort, redisLivePass, redisLiveDb);
    }

    /**
     * 創(chuàng)建 RedisTemplate
     */
    public RedisTemplate<Object, Object> createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

        Jackson2JsonRedisSerializer<?> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        serializer.setObjectMapper(objectMapper);

        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * 創(chuàng)建 StringRedisTemplate
     */
    public StringRedisTemplate createStringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
        return stringRedisTemplate;
    }

    /**
     * 創(chuàng)建 StringRedisTemplate
     */
    public StringRedisTemplate createStringRedisTemplate(String host, int port, String password, int database) {
        // 基本配置
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(host);
        configuration.setPort(port);
        configuration.setDatabase(database);
        if (ObjectUtils.isNotEmpty(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);

        // Lettuce Pool
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
        builder.poolConfig(genericObjectPoolConfig);
        builder.commandTimeout(Duration.ofSeconds(timeout));
        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(configuration, builder.build());
        connectionFactory.afterPropertiesSet();

        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(connectionFactory);
        return stringRedisTemplate;
    }

}

這里注意

@Bean(name = "liveStringRedisTemplate")

將類交給spring,后面在引用會(huì)根據(jù)名稱引入。

使用

在使用的時(shí)候我們使用@Qualifier顯示引用對(duì)象:

	// redis-1
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    // redis-2
    @Autowired
    @Qualifier("liveStringRedisTemplate")
    private RedisTemplate<String, String> liveStringRedisTemplate;

下面我們可以使用RedisTemplate愉快地操作redis了!到這里springboot配置多數(shù)據(jù)源就成功了,這里的RedisTemplate還可以整合進(jìn)工具類,讓操作更加方便!

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java 兩個(gè)數(shù)組合并的幾種方法

    java 兩個(gè)數(shù)組合并的幾種方法

    本篇文章主要介紹了java 兩個(gè)數(shù)組合并的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-08-08
  • Java中線程安全有哪些實(shí)現(xiàn)思路

    Java中線程安全有哪些實(shí)現(xiàn)思路

    在 Java 多線程編程中,線程安全是一個(gè)非常重要的概念,本文主要介紹了Java中線程安全有哪些實(shí)現(xiàn)思路,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2023-05-05
  • IDEA Debug啟動(dòng)tomcat報(bào)60659端口占用錯(cuò)誤的解決

    IDEA Debug啟動(dòng)tomcat報(bào)60659端口占用錯(cuò)誤的解決

    工作中將開發(fā)工具由Eclipse轉(zhuǎn)為IntelliJ IDEA,在使用過程中遇到許多問題,其中60659端口占用錯(cuò)誤對(duì)于不熟悉IDEA的開發(fā)者來說或許會(huì)比較頭痛,本文就來解決一下這個(gè)問題
    2018-11-11
  • Java面試題沖刺第五天--基礎(chǔ)篇2

    Java面試題沖刺第五天--基礎(chǔ)篇2

    這篇文章主要為大家分享了最有價(jià)值的三道java面試題,涵蓋內(nèi)容全面,包括數(shù)據(jù)結(jié)構(gòu)和算法相關(guān)的題目、經(jīng)典面試編程題等,感興趣的小伙伴們可以參考一下
    2021-07-07
  • 圖文詳解java內(nèi)存回收機(jī)制

    圖文詳解java內(nèi)存回收機(jī)制

    這篇文章主要以圖文結(jié)合的方式為大家詳細(xì)介紹了java內(nèi)存回收機(jī)制,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • MybatisPlus分頁失效不起作用的解決

    MybatisPlus分頁失效不起作用的解決

    在使用MybatisPlus的selectPage時(shí)發(fā)現(xiàn)分頁不起作用,每次返回的都是全部的數(shù)據(jù),本文就來介紹一下MybatisPlus分頁失效不起作用的解決,感興趣的可以了解一下
    2024-03-03
  • SWT(JFace)體驗(yàn)之Sash(活動(dòng)控件)

    SWT(JFace)體驗(yàn)之Sash(活動(dòng)控件)

    SWT(JFace)體驗(yàn)之Sash(活動(dòng)控件)
    2009-06-06
  • springboot的java配置方式(實(shí)例講解)

    springboot的java配置方式(實(shí)例講解)

    下面小編就為大家分享一篇實(shí)例講解springboot的java配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2017-11-11
  • JAVA HTTP反向代理實(shí)現(xiàn)過程詳解

    JAVA HTTP反向代理實(shí)現(xiàn)過程詳解

    這篇文章主要介紹了JAVA HTTP反向代理實(shí)現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • springboot Jpa多數(shù)據(jù)源(不同庫)配置過程

    springboot Jpa多數(shù)據(jù)源(不同庫)配置過程

    這篇文章主要介紹了springboot Jpa多數(shù)據(jù)源(不同庫)配置過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05

最新評(píng)論