1.先配置spring-data-redis
首先是依赖
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.8.4.RELEASE</version> </dependency>
redisconfig 配置类
@Configuration @PropertySource("classpath:irongbei.properties") public class RedisConfig extends JCacheConfigurerSupport { @Autowired private Environment environment; @Bean public RedisConnectionFactory redisConnectionFactory() { JedisConnectionFactory fac = new JedisConnectionFactory(); fac.setHostName(environment.getProperty("redis.host")); fac.setPort(Integer.parseInt(environment.getProperty("redis.port"))); fac.setPassword(environment.getProperty("redis.password")); fac.setTimeout(Integer.parseInt(environment.getProperty("redis.timeout"))); // fac.getPoolConfig().setMaxIdle(Integer.parseInt(environment.getProperty("redis.maxIdle"))); // fac.getPoolConfig().setMaxTotal(Integer.parseInt(environment.getProperty("redis.maxTotal"))); // fac.getPoolConfig().setMaxWaitMillis(Integer.parseInt(environment.getProperty("redis.maxWaitMillis"))); // fac.getPoolConfig().setMinEvictableIdleTimeMillis( // Integer.parseInt(environment.getProperty("redis.minEvictableIdleTimeMillis"))); // fac.getPoolConfig() // .setNumTestsPerEvictionRun(Integer.parseInt(environment.getProperty("redis.numTestsPerEvictionRun"))); // fac.getPoolConfig().setTimeBetweenEvictionRunsMillis( // Integer.parseInt(environment.getProperty("redis.timeBetweenEvictionRunsMillis"))); // fac.getPoolConfig().setTestOnBorrow(Boolean.parseBoolean(environment.getProperty("redis.testOnBorrow"))); // fac.getPoolConfig().setTestWhileIdle(Boolean.parseBoolean(environment.getProperty("redis.testWhileIdle"))); return fac; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, String> redis = new RedisTemplate<>(); // 设置redis的String/Value的默认序列化方式 DefaultStrSerializer defaultStrSerializer = new DefaultStrSerializer(); redis.setKeySerializer(defaultStrSerializer); redis.setValueSerializer(defaultStrSerializer); redis.setHashKeySerializer(defaultStrSerializer); redis.setHashValueSerializer(defaultStrSerializer); redis.setConnectionFactory(redisConnectionFactory); redis.afterPropertiesSet(); return redis; } } class DefaultStrSerializer implements RedisSerializer<Object> { private final Charset charset; public DefaultStrSerializer() { this(Charset.forName("UTF8")); } public DefaultStrSerializer(Charset charset) { Assert.notNull(charset, "Charset must not be null!"); this.charset = charset; } @Override public byte[] serialize(Object o) throws SerializationException { return o == null ? null : String.valueOf(o).getBytes(charset); } @Override public Object deserialize(byte[] bytes) throws SerializationException { return bytes == null ? null : new String(bytes, charset); } }
View Code