当前位置:   article > 正文

Lettuce 客户端自定义 RedisTemplate

Lettuce 客户端自定义 RedisTemplate

背景:公司项目有两个 redis,一个是 sso 使用,一个是业务使用,为了区分,需要自定义 RedisTemplate

  1. 自定义 RedisTemplate
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author liuyuan
 * @version ItemBuyerRedisTemplate.java, v 0.1 2024-03-15 16:27
 */
public class ItemBuyerRedisTemplate extends StringRedisTemplate {
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. 配置 RedisTemplate
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author liuyuan
 * @version ItemRedisConfiguration.java, v 0.1 2024-03-15 15:49
 */
@Configuration
public class ItemRedisConfiguration {

    @Value("${item.buyer_redis_host}")
    private String buyerRedisHost;
    @Value("${spring-redis-port:6379}")
    private int buyerRedisPort;
    @Value("${spring-redis-database:1}")
    private int buyerRedisDatabase;

    @Bean
    public ItemBuyerRedisTemplate itemBuyerRedisTemplate() {

        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(buyerRedisHost);
        redisStandaloneConfiguration.setPort(buyerRedisPort);
        redisStandaloneConfiguration.setDatabase(buyerRedisDatabase);
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration);
        // 初始化
        lettuceConnectionFactory.afterPropertiesSet();

        ItemBuyerRedisTemplate stringRedisTemplate = new ItemBuyerRedisTemplate();
        stringRedisTemplate.setConnectionFactory(lettuceConnectionFactory);
        return stringRedisTemplate;
    }

    @Primary
    @Bean
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        return new StringRedisTemplate(redisConnectionFactory);
    }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/948810
推荐阅读
相关标签
  

闽ICP备14008679号