项目结构
流程
先调用本地缓存进行查找,没有查看redis缓存,没有查数据库,同时添加到redis和本地缓存中
代码
StudentServiceImpl
package com.wunaiieq.tmp_redis_20241217.service;
import com.wunaiieq.tmp_redis_20241217.entity.Student;
import com.wunaiieq.tmp_redis_20241217.mapper.StudentMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.cache.*;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;
@Service
public class StudentServiceImpl implements StudentService{
@Autowired
private StudentMapper studentMapper;
@Autowired
private RedisService redisService;
/**
* 本地缓存
*/
private LoadingCache<String, Student> Cache = CacheBuilder.newBuilder()
//设置并发级别为16,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(16)
//设置缓存容器的初始容量为1000
.initialCapacity(1000)
//设置缓存最大容量为10000,超过10000之后就会按照LRU最近虽少使用算法来移除缓存项
.maximumSize(10000)
//设缓存1小时没被使用就过期
.expireAfterAccess(1, TimeUnit.HOURS)
//设置要统计缓存的命中率
.recordStats()
//设置缓存的移除通知
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {
System.out.println(notification.getKey() + " 被移除了,原因: " + notification.getCause());
}
})
.build(new CacheLoader<String, Student>() {
@Override
public Student load(String key) throws Exception {
// 如果没有缓存先从redis中获取
Student student0 = (Student) redisService.get("user:" + key);
if (student0 != null) {
return student0;
}
// 2、redis中没有查询数据库
Student student = studentMapper.selectById(key);
// 4、加入redis分布式缓存
redisService.set("student:" + key, student);
return student;
}
});
/**
* 根据用户id查询用户
*
* @param id
* @return
*/
@SneakyThrows
@Override
public Student getById(Long id) {
// 1、从本地缓存获取
Student o = Cache.get(id + "");
return o;
}
}
RedisService、RedisConfig
博客链接
Controller
package com.wunaiieq.tmp_redis_20241217.controller;
import com.wunaiieq.tmp_redis_20241217.entity.Student;
import com.wunaiieq.tmp_redis_20241217.service.StudentService;
import com.wunaiieq.tmp_redis_20241217.service.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Studentcontroller {
@Autowired
private StudentServiceImpl studentServiceImpl;
@GetMapping("/getByid")
public Student getStudent(long id){
return studentServiceImpl.getById(id);
}
}
StudentService
package com.wunaiieq.tmp_redis_20241217.service;
import com.wunaiieq.tmp_redis_20241217.entity.Student;
import lombok.SneakyThrows;
public interface StudentService {
@SneakyThrows
Student getById(Long id);
}
StudentMapper
package com.wunaiieq.tmp_redis_20241217.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wunaiieq.tmp_redis_20241217.entity.Student;
public interface StudentMapper extends BaseMapper <Student>{
}