在Java中使用redisTemplate操作缓存(5)

Cursor<Map.Entry<String, String>> cursor = redisTemplate.opsForHash().scan("test", ScanOptions.scanOptions().match("SCAN").build());
if (cursor.hasNext()) {
while (cursor.hasNext()) {
Map.Entry<String, String> entry = cursor.next();
System.out.println(entry.getValue()); // [5, 6, 7, 8]
}
}

引入redisTemplate
如果大家看懂了怎么用,就可以将redisTemplate引入项目中了。

引入pom依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>

新建配置文件
然后需要新建一个RedisConfig配置文件。


package com.detectivehlh;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**
•RedisConfig

•@author Lunhao Hu

•@date 2019-01-17 15:12br/>**/
@Configuration
public class RedisConfig {br/>@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//redis序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
jackson2JsonRedisSerializer.setObjectMapper(om);

StringRedisTemplate template = new StringRedisTemplate(factory);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;

}
}


注入
将redisTemplate注入到需要使用的地方。

@Autowired
private RedisTemplate redisTemplate;

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/66b7e7c1414f63dcd3776c4e34beeba1.html