Springboot RedisTemplate 設(shè)置key 前綴

springboot 連接redis 并設(shè)置key前綴

properties中配置

#redis
redis.masterClusterNodes=10.40.57.197:7000;10.40.57.198:7002;10.40.57.199:7004
redis.slaveClusterNodes=10.40.57.197:7001;10.40.57.198:7003;10.40.57.199:7005
redis.maxTotal=50
redis.maxIdle=10
redis.minIdle=1
redis.maxWaitMillis=1000
redis.testOnBorrow=true
redis.testOnReturn=true
redis.timeout=10000
redis.lockExpireSeconds=5
redis.soTimeout=1000
redis.maxAttempts=3
redis.password=123456
redis.clientName=clientName

redis.keyPrefix=0000-->

讀取配置文件內(nèi)容:

@Component
@ConfigurationProperties(prefix = "redis")
@PropertySource("classpath:redis.properties")
public class RedisProperties {
    /**
     * master 節(jié)點(diǎn)數(shù)據(jù)
     */
    private String masterClusterNodes;
    /**
     * slave 節(jié)點(diǎn)數(shù)據(jù)
     */
    private String slaveClusterNodes;
    /**
     * 連接超時(shí)時(shí)間
     */
    private int timeout;
    /**
     * 獲取數(shù)據(jù)超時(shí)時(shí)間
     */
    private int soTimeout;
    /**
     * 出現(xiàn)異常最大重試次數(shù)
     */
    private int maxAttempts;
    /**
     * 連接時(shí)使用的密碼
     */
    private String password;

    private int maxTotal;
    private int maxIdle;
    private int minIdle;
    private int maxWaitMillis;

    private boolean testOnBorrow;
    private boolean testOnReturn;

    /**
     * key前綴
     */
    private String keyPrefix;
    sets,gets
    
}

自定義StringSerializer

這個(gè)還是需要優(yōu)化的

@Component
public class MyStringSerializer implements RedisSerializer<String> {

    private final Logger logger = LoggerFactory.getLogger ( this.getClass () );

    @Autowired
    private RedisProperties redisProperties;

    private final Charset charset;

    public MyStringSerializer() {
        this ( Charset.forName ( "UTF8" ) );
    }

    public MyStringSerializer(Charset charset) {
        Assert.notNull ( charset, "Charset must not be null!" );
        this.charset = charset;
    }

    @Override
    public String deserialize(byte[] bytes) {
        String keyPrefix = redisProperties.getKeyPrefix ();
        String saveKey = new String ( bytes, charset );
        int indexOf = saveKey.indexOf ( keyPrefix );
        if (indexOf > 0) {
            logger.info ( "key缺少前綴" );
        } else {
            saveKey = saveKey.substring ( indexOf );
        }
        logger.info ( "saveKey:{}",saveKey);
        return (saveKey.getBytes () == null ? null : saveKey);
    }

    @Override
    public byte[] serialize(String string) {
        String keyPrefix = redisProperties.getKeyPrefix ();
        String key = keyPrefix + string;
        logger.info ( "key:{},getBytes:{}",key, key.getBytes ( charset ));
        return (key == null ? null : key.getBytes ( charset ));
    }
}

redisConfig 配置

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    private final Logger logger = LoggerFactory.getLogger ( this.getClass () );

    @Autowired
    private RedisProperties redisProperties;
    @Autowired
    private MyStringSerializer myStringSerializer;
    
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory ( redisClusterConfiguration (),
                jedisPoolConfig () );
        jedisConnectionFactory.setPassword ( redisProperties.getPassword () );
        jedisConnectionFactory.setTimeout ( redisProperties.getTimeout () );
        return jedisConnectionFactory;
    }

    @Bean
    public RedisClusterConfiguration redisClusterConfiguration() {
        String[] ipPorts = redisProperties.getClusterNodes ().split ( ";" );
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration ( Arrays.asList ( ipPorts
        ) );
        return redisClusterConfiguration;
    }

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = BeanMapperUtil.map ( redisProperties,
                JedisPoolConfig.class );
        return jedisPoolConfig;
    }


    /**
     * 配置cacheManage
     * 設(shè)置超時(shí)時(shí)間  1小時(shí)
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager ( redisTemplate );
        redisCacheManager.setDefaultExpiration ( 60 * 60 );
        return redisCacheManager;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate ( jedisConnectionFactory () );
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer ( Object.class );
        ObjectMapper om = new ObjectMapper ();
        om.setVisibility ( PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY );
        om.enableDefaultTyping ( ObjectMapper.DefaultTyping.NON_FINAL );
        jackson2JsonRedisSerializer.setObjectMapper ( om );
        template.setKeySerializer ( myStringSerializer );
        template.setHashKeySerializer ( myStringSerializer );
        template.setValueSerializer ( jackson2JsonRedisSerializer );
        template.afterPropertiesSet ();
        return template;
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,553評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,272評(píng)論 6 342
  • 每個(gè)人都曾有過(guò)青春,誰(shuí)沒(méi)有在那一段時(shí)光中留下遺憾,從懵懂的少年慢慢地成長(zhǎng)為成熟的青年,這其中又有多少坎坷與辛酸。 ...
    卜愚閱讀 163評(píng)論 0 0
  • 看著廣闊的江面,漸漸遠(yuǎn)去的船只,還有遠(yuǎn)方模糊的建筑,真應(yīng)了李白的詩(shī)句: 孤帆遠(yuǎn)影碧空盡,唯見(jiàn)長(zhǎng)江天際流。
    鐘離南子閱讀 494評(píng)論 2 0
  • 雙11來(lái)啦,雙11不知從什么時(shí)候開(kāi)始已經(jīng)變成全民和電商的狂歡。最近你是不是已經(jīng)堆滿了購(gòu)物車,就等著雙11那天下手呢...
    大話華爾街閱讀 455評(píng)論 0 0

友情鏈接更多精彩內(nèi)容