1、在pom.xml 添加redis依赖
<!-- redis 依赖配置 -- >
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、新增实体类
package com.example.demo.model;
import java.io.Serializable;
public class Student implements Serializable {
private int id;
private String name;
private int age;
}
3、编写Controller
package com.example.demo.controller;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService service;
@GetMapping("/count")
@ResponseBody
public Integer countHandler() {
return service.findStudentsCount();
}
}
4、新增service接口
package com.example.demo.service;
import com.example.demo.model.Student;
import java.util.List;
public interface StudentService {
Integer findStudentsCount();
}
5、新增service 的实现类
package com.example.demo.service;
import com.example.demo.dao.StudentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao dao;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@Override
public Integer findStudentsCount() {
// 获取Redis操作对象
BoundValueOperations<Object, Object> ops = redisTemplate.boundValueOps("count");
// 从Redis中获取指定key的value
Object count = ops.get();
// 双重检测
if(count == null){
synchronized (this){
count = ops.get();
if(count == null){
// 从DB中查询
count = dao.selectStudentsCount();
// 将查询结果存档到Redis,并指定过期时限
ops.set(count,10, TimeUnit.SECONDS);
}
}
}
return (Integer) count;
}
}
6、新增dao接口
package com.example.demo.dao;
import com.example.demo.model.Student;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface StudentDao {
Integer selectStudentsCount();
}
7、新增xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.StudentDao">
<select id="selectStudentsCount" resultType="int">
select count(id) from student
</select>
</mapper>
8、访问地址
http://localhost:8080/student/count
详细的demo可以见:https://download.csdn.net/download/leixialx/24312833