Redis 是一个开源(BSD许可)的、基于内存的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持字符串、哈希表、列表、集合、有序集合,位图,hyperloglogs 7种数据类型的存储。
本篇文章的讲述的重点不在Redis本身,所以这里就采用了一种比较方便的安装方式——使用Docker安装Redis。这里安装的是当前最新版本的Redis。
# 安装
$ docker pull redis
# 运行
$ docker run -p 6379:6379
--name redis
-v /Users/wanggc/Data/redis/data:/data
-v /Users/wanggc/Data/redis/conf/redis.conf:/etc/redis/redis.conf
-d redis redis-server /etc/redis/redis.conf
命令说明:
org.springframework.boot
spring-boot-starter-data-redis
${spring-boot.version}
io.lettuce
lettuce-core
redis.clients
jedis
org.apache.commons
commons-pool2
2.9.0
默认的情况下,spring-boot-starter-data-redis 会依赖 Lettuce 客户端驱动,笔者这里选择使用的是 Jedis 客户端驱动。所以在代码中需要使用了
在application.properties文件中加入如下代码:
#配置Redis服务器属性
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
#Redis连接超时时间,单位毫秒
spring.redis.timeout=1000
#配置连接池属性
spring.redis.jedis.pool.min-idle=5
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-wait=2000
这里我们配置了连接池和服务器的属性,用以连接Redis服务器。
@Configuration
public class RedisConfig {
@Bean(name = "redisTemplate")
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(factory);
RedisSerializer jackson2JsonRedisSerializer = getJacksonSerializer();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson的序列化方式
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
/**
* redis的json序列化
*/
private RedisSerializer getJacksonSerializer() {
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
return new GenericJackson2JsonRedisSerializer(om);
}
}
2.4 使用RedisTemplate操作Redis数据类型
// 1. 注入RedisTemplate
@Resource
private RedisTemplate redisTemplate;
// 2. 添加缓存
redisTemplate.opsForValue().set(redisKey, user);
// 3. 获取缓存数据
User user = redisTemplate.opsForValue().get(redisKey);
页面更新:2024-04-03
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号