0.maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifact>spring-boot-starter</artifact>
</dependency>
1.在application.properties配置redis
这里写的都是默认配置:
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=0
2.配置StringRedisTemplate Bean
@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;
}
}
3.使用redis
@RestController
@Api(tags="Redis 测试")
@RequestMapping(value="/redis")
public class RedisController{
private String StringRedisTemplate redisTemplate;
@PostMapping(value="/set")
@ApiOperation("存值")
public String set(@Valid@RequestParam String key,@Valid@RequestParam String value){
redisTemplate.opsForValue().set(key,value);
Map<String, Object> result=new HashMap<>();
result.put("code","111");
result.put("msg","set successful!");
return result;
}
@GetMapping(value="/get")
@ApiOperation("获取值")
public String get(@Valid@RequestParam String key){
Map<String,Object> result=new HashMap<>();
result.put("result","key="+key+"value"+redisTemplate.opsForValue().get(key));
result.put("msg","get successful!");
return result;
}
}