SpringBoot下自定义缓存

it2025-02-06  28

SpringBoot下自定义缓存

1.依赖导入

<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

2.service

模拟从数据库中获取数据并进行相加处理 接口

public interface DemoService { Integer add(Integer a,Integer b); }

实现类 定义了内部类,这里简化redis数据缓存,用Map集合代替

@Service public class DemoServiceImpl implements DemoService { //自定义缓存机制 //存放请求参数和结果 private Map<Param,Integer> map = new HashMap<>(); //将参数封装到类中 @Data //重写hashcode和equal方法,保证map中只有一个对应的key和value @AllArgsConstructor private class Param{ private Integer a; private Integer b; } @Override public Integer add(Integer a, Integer b) { //这里判断缓存中是否存在,如果存在则直接从缓存中获取 Param param = new Param(a,b); if (map.containsKey(param)){ return map.get(param); } //模拟从数据库中进行查询,时间延迟5秒 try { Thread.currentThread().sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } map.put(param,a+b); return a+b; } }

3.controller

@RestController public class DemoController { @Autowired private DemoService demoService; @GetMapping("/demo1/{a}/{b}") public Integer m1(@PathVariable("a") Integer a, @PathVariable("b") Integer b){ return demoService.add(a,b); } }

4.结果:

在第一次访问时数据处理需要5s,后续的请求都是秒传,当然这里没有处理如果两个参数位置倒置的情况

最新回复(0)