Springboot Redis設置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-->

讀取配置文件內容:

@Component
@ConfigurationProperties(prefix = "redis")
@PropertySource("classpath:redis.properties")
public class RedisProperties {
    /**
     * master 節點數據
     */
    private String masterClusterNodes;
    /**
     * slave 節點數據
     */
    private String slaveClusterNodes;
    /**
     * 連接超時時間
     */
    private int timeout;
    /**
     * 獲取數據超時時間
     */
    private int soTimeout;
    /**
     * 出現異常最大重試次數
     */
    private int maxAttempts;
    /**
     * 連接時使用的密碼
     */
    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

這個還是需要優化的

@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
     * 設置超時時間  1小時
     *
     * @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;
    }
}

到此這篇關於Springboot Redis設置key前綴的方法步驟的文章就介紹到這瞭,更多相關Springboot Redis key前綴內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!