目录
第三步:选择Spring Data Redis进行操作Redis数据库
第一步:引入依赖
<!--SpringDataRedis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--common-pool-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--Jackson依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
第二步:配置Redis信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.136.132/mydb
username: root
password: 1234
type: com.alibaba.druid.pool.DruidDataSource
redis:
database: 0
host: 192.168.136.132
port: 6379
password: pz030812...
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: 100ms
第三步:选择Spring Data Redis进行操作Redis数据库
①操作String类型数据(用的少)
@Autowired
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/redismessge")
public JsonResult Redismsg(){
//操作String数据
//增,改
stringRedisTemplate.opsForValue().set("jxxy","计科一班");
//查
String jxxy = stringRedisTemplate.opsForValue().get("jxxy");
System.out.println("jxxy = " + jxxy);
//删
stringRedisTemplate.opsForValue().getAndDelete("jxxy");
return new JsonResult();
}
②操作Object类型数据(重要!!!)
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
//序列化工具
private static final ObjectMapper mapper= new ObjectMapper();
@PostMapping("/redismessge_1")
public JsonResult Redismsg_1(@RequestBody Student student) throws JsonProcessingException {
//使用自动序列化
redisTemplate.opsForValue().set("jxxy_01",student);
Object jxxy_01 = redisTemplate.opsForValue().get("jxxy_01");
System.out.println("jxxy_01 = " + jxxy_01);
//手动序列化
String json = mapper.writeValueAsString(student);
stringRedisTemplate.opsForValue().set("jxxy_02",json);
json = stringRedisTemplate.opsForValue().get("jxxy_02");
Student jxxy_02 = mapper.readValue(json, Student.class);
System.out.println("jxxy_02 = " + jxxy_02);
return new JsonResult();
}
postman发送请求:
idea输出数据:
注:自动序列化和手动序列化的区别:如果单在java客户端看的话,二者并无明显区别,但是从Redis数据库中看的话就会发现在自动序列化的方式在redis数据库中每个数据前面都会增加一串地址,而手动的则是清晰的数据;而且使用Redistemplate时,对象类要加 implements Serializable
先看自动序列化redis的存储情况:
再看手动序列化redis的存储情况:
③操作Hash,Set,List类型数据
这几类数据用的比较少,可以去Redis基础讲解中查看,这里就不做代码演示
学习路线:
SpringBoot---------@Value,@ConfigurationProperyies以及多环境开发配置