1.pom依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2. application.properties
配置加入redis相关配置
# REDIS (RedisProperties) # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=127.0.0.1 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=0
3.一般上通过以上两步就可使用了,但工作中一般上是通过 StringRedisTemplate
(默认采用 string
的序列化,保存key和值时都是通过此序列化策略)接口进行操作,所以这里直接配置了 StringRedisTemplate
bean类。
RedisConfig.java
/** * * @author oKong * */ @Configuration public class RedisConfig { /** * 定义 StringRedisTemplate ,指定序列化和反序列化的处理类 * @param factory * @return */ @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer<Object> 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; } }
4.编写控制类,测试集成是否生效。
RedisController.java
@RestController @RequestMapping("/redis") @Api(tags = "redis 测试API") public class RedisController { @Autowired StringRedisTemplate redisTemplate; @GetMapping("set/{key}/{value}") @ApiOperation(value="设置缓存") public String set(@PathVariable("key")String key,@PathVariable("value") String value) { //注意这里的 key不能为null spring 内部有检验 redisTemplate.opsForValue().set(key, value); return key + "," + value; } @GetMapping("get/{key}") @ApiOperation(value="根据key获取缓存") public String get(@PathVariable("key") String key) { return "key=" + key + ",value=" + redisTemplate.opsForValue().get(key); } }