SpringBoot整合Redis
1.添加redis的起步依赖
<!-- 配置使用redis启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置redis的连接信息
这里可以写在application.properties里,也可以写在application-myredis.properties里,还可以写在.yaml或者.yml里。
以下是我的application.properties
#数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.137.10:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
3. Controller实例
下面展示一些 内联代码片
。
@RequestMapping("/list")
@ResponseBody
public Map<String,Object> getUserList(){
Map<String,Object> map = new HashMap<>();
List<User> userList = userService.getUserList();
//从redis缓存中获得指定的数据
String userListData = redisTemplate.boundValueOps("user.findAll").get();
//如果redis里查不到
if(null==userListData) {
//查询数据库获得数据
//转换成json格式字符串
userListData = JSONUtil.toJSON(userList);
//将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库
redisTemplate.boundValueOps("user.findAll").set(userListData);
System.out.println("===============从数据库获得数据===============");
//保存到redis
redisTemplate.boundValueOps("user.findAll").set(userListData);
}else{
System.out.println("===============从redis缓存中获得数据===============");
}
map.put("userListData",userList);
System.out.println("查询用户列表");
return map;
}