spring4 注解方式集成redis

 

 

@Configuration
public class RedisConfig {

    @Autowired
    private Environment env;
    @Bean
    public RedisConnectionFactory redisCF() {
        JedisConnectionFactory cf = new JedisConnectionFactory();
        cf.setHostName(env.getProperty("redis.host"));
        cf.setPort(Integer.valueOf(env.getProperty("redis.port")));
        cf.setPassword(env.getProperty("redis.pass"));
        cf.afterPropertiesSet();
        return cf;
    }
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory cf) {
        RedisTemplate redis = new RedisTemplate<>();
        redis.setConnectionFactory(cf);
        //设置 key value 序列号类型
//        redis.setKeySerializer(stringRedisSerializer());
//        redis.setValueSerializer(stringRedisSerializer());
//        redis.setHashKeySerializer(stringRedisSerializer());
//        redis.setHashValueSerializer(stringRedisSerializer());
        redis.afterPropertiesSet();
        return redis;
    }
    
    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory cf) {
        return new StringRedisTemplate(cf);

    }

}


使用时 直接 注入RedisTemplate 或者 StringRedisTemplate

 @Autowired
 private StringRedisTemplate stringRedisTemplate;



你可能感兴趣的:(Spring,redis)