1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置yml文件
spring:
redis:
host: 192.168.***.*** #redis的IP地址
port: 6379 #端口号
database: 0 #选择redis的库(0~15)
3、StringRedisTemplate
@Api(tags = "redis缓存测试")
@RestController
@RequestMapping("/api")
public class RedisController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
//get查询图书库存
@GetMapping("/getBookStore")
public HttpResp getBookStore(){
String bookStore = stringRedisTemplate.opsForValue().get("book");
return HttpResp.success("redis图书库存数量:"+bookStore);
}
4、对象的存储问题
转化为字符串:
//hash put 添加车辆信息
@ApiOperation(value = "addCarInRedis",notes = "添加新车辆信息")
@PostMapping("/addCarInRedis")
public HttpResp<String> addCarInRedis(Car car){
stringRedisTemplate.opsForHash().put(
"mycar","mycar:"+car.getId(),car.toString());
return HttpResp.success("车辆信息:"+car.getId()+"添加成功");
}
处理办法:在RedisTemplate中转换:
新建RedisConfig 配置类
@Configuration
@Slf4j
public class RedisConfig {
//配置redis类型转换json
@Bean
public RedisTemplate<String,Object> objectRedisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//hash key hashkey value
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
log.debug("redis配置完成:{}",redisTemplate);
return redisTemplate;
}
}
自动注入:
@Autowired
private RedisTemplate<String,Object> objectRedisTemplate;
调用objectRedisTemplate方法,测试:
//hash put 添加车辆信息(使用配置类进行json格式转换)
@ApiOperation(value = "addCarInRedisx",notes = "添加新车辆信息x")
@PostMapping("/addCarInRedisx")
public HttpResp<String> addCarInRedisx(Car car){
objectRedisTemplate.opsForHash().put(
"mycarx","mycarx:"+car.getId(),car.toString());
return HttpResp.success("车辆信息x:"+car.getId()+"添加成功");
}