引入对应的 pom 坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.10.2</version>
<scope>compile</scope>
</dependency>
配置一个配置类
@Configuration
@EnableCaching
public class LettuceRedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
开始存放
@Autowired
private RedisTemplate redisTemplate;
@Override
public void getRedisListGoods() {
//查询到的集合
List<GoodsVo> list = getGoods();
//获取 redis 操作对象
//泛型类型(key,对应的实体类)
ListOperations<String, GoodsVo> ops = redisTemplate.opsForList();
//开始存放
list.forEach(k -> {
ops.leftPush(k.getGoodsName(), k);
});
}
模糊查询
/**
* 模糊查询
* @param matchKey 关键字
* @return
*/
@Override
public List<GoodsVo> scan(String matchKey) {
//搜索到的 key 值存放的集合
Set<String> keys = new LinkedHashSet<>();
//开始搜索,数据存储在上面的 set 集合中
redisTemplate.execute((RedisConnection connection) -> {
try (Cursor<byte[]> cursor = connection.scan(
ScanOptions.scanOptions()
.count(Long.MAX_VALUE)
//* 号通配符的作用
.match("*"+matchKey+"*")
.build()
)) {
cursor.forEachRemaining(item -> {
keys.add(RedisSerializer.string().deserialize(item));
});
return keys;
} catch (Exception e) {
throw new RuntimeException(e);
}
});
//获取一个 redis 操作对象
ListOperations ops = redisTemplate.opsForList();
//设置一个存放查询数据的集合
List<GoodsVo> voList = new ArrayList<>();
//遍历搜索的 key 并存放到集合中
keys.forEach(key ->{
voList.add((GoodsVo) ops.index(key,-1));
});
return voList;
}
版权声明:本文为qq_37109411原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。