spring boot2 集成Redis
阿新 • • 發佈:2018-06-28
cee nds time con 構造器 repo 構造 source .so
1. 引入依賴
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring.data.redis.version>2.0.8.RELEASE</spring.data.redis.version><!--1.8.7.RELEASE--> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${spring.data.redis.version}</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> </dependencies>
2. application.yml中添加配置
spring: redis: #數據庫索引 database: 0 host: 127.0.0.1 port: 6379 password: jedis: pool: #最大連接數 max-active: 8 #最大阻塞等待時間(負數表示沒限制) max-wait: -1 #最大空閑 max-idle: 8 #最小空閑 min-idle: 0 #連接超時時間 timeout: 10000
3. RedisConfiguration
@Configuration @EnableCaching public class RedisConfiguration extends CachingConfigurerSupport { @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } // @Bean // public CacheManager cacheManager(RedisTemplate redisTemplate) { // RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate); // return redisCacheManager; // } // // // @Bean // public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { // ////解決鍵、值序列化問題 // StringRedisTemplate template = new StringRedisTemplate(factory); // 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.setValueSerializer(jackson2JsonRedisSerializer); // template.afterPropertiesSet(); // return template; // } /* spring-data-redis 版本不同,方法也不一樣 上面是1.5 下面是2.0 */ @Bean public CacheManager cacheManager(RedisConnectionFactory connectionFactory) { RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).build(); return redisCacheManager; } /** * @Description: 防止redis入庫序列化亂碼的問題 * @return 返回類型 * @date 2018/4/12 10:54 */ @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer());//key序列化 redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class)); //value序列化 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; }
4. RedisService
@Component
public class RedisService<HK, V> {
// 在構造器中獲取redisTemplate實例, key(not hashKey) 默認使用String類型
private RedisTemplate<String, V> redisTemplate;
// 在構造器中通過redisTemplate的工廠方法實例化操作對象
private HashOperations<String, HK, V> hashOperations;
private ListOperations<String, V> listOperations;
private ZSetOperations<String, V> zSetOperations;
private SetOperations<String, V> setOperations;
private ValueOperations<String, V> valueOperations;
// IDEA雖然報錯,但是依然可以註入成功, 實例化操作對象後就可以直接調用方法操作Redis數據庫
@Autowired
public RedisService(RedisTemplate<String, V> redisTemplate) {
this.redisTemplate = redisTemplate;
this.hashOperations = redisTemplate.opsForHash();
this.listOperations = redisTemplate.opsForList();
this.zSetOperations = redisTemplate.opsForZSet();
this.setOperations = redisTemplate.opsForSet();
this.valueOperations = redisTemplate.opsForValue();
}
public void hashPut(String key, HK hashKey, V value) {
hashOperations.put(key, hashKey, value);
}
public Map<HK, V> hashFindAll(String key) {
return hashOperations.entries(key);
}
public V hashGet(String key, HK hashKey) {
return hashOperations.get(key, hashKey);
}
public void hashRemove(String key, HK hashKey) {
hashOperations.delete(key, hashKey);
}
public Long listPush(String key, V value) {
return listOperations.rightPush(key, value);
}
public Long listUnshift(String key, V value) {
return listOperations.leftPush(key, value);
}
public List<V> listFindAll(String key) {
if (!redisTemplate.hasKey(key)) {
return null;
}
return listOperations.range(key, 0, listOperations.size(key));
}
public V listLPop(String key) {
return listOperations.leftPop(key);
}
public void setValue(String key, V value) {
valueOperations.set(key, value);
}
public void setValue(String key, V value, long timeout) {
ValueOperations<String, V> vo = redisTemplate.opsForValue();
vo.set(key, value, timeout, TimeUnit.MILLISECONDS);
}
public V getValue(String key) {
return valueOperations.get(key);
}
public void remove(String key) {
redisTemplate.delete(key);
}
public boolean expire(String key, long timeout, TimeUnit timeUnit) {
return redisTemplate.expire(key, timeout, timeUnit);
}
5. test
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
RedisService redisService;
@Test
public void findAllUsers() {
redisService.setValue("key","hello");
}
@Test
public void findAllUsers2() {
System.out.println("get key value:"+ redisService.getValue("key"));
}
}
說明
- 以上是具體的配置,如果沒有引入redis.clients.jedis 依賴,則會報No beans of ‘RedisConnectionFactory‘ type found.
版本則2.9.0 如果 版本低,則會報其它錯誤 - spring-data-redis 這個版本分為 1.x 和 2.x 版本變動挺多,不同版本方法也不一樣
spring boot2 集成Redis