57 if (!StringUtils.isEmpty(oldUserInfo.getAge())) {
58 oldUserInfo.setAge(userInfo.getAge());
59 }
60 if (!StringUtils.isEmpty(oldUserInfo.getName())) {
61 oldUserInfo.setName(userInfo.getName());
62 }
63 if (!StringUtils.isEmpty(oldUserInfo.getSex())) {
64 oldUserInfo.setSex(userInfo.getSex());
65 }
66 // 将新的对象存储,更新旧对象信息
67 userInfoMap.put(oldUserInfo.getId(), oldUserInfo);
68 // 替换缓存中的值
69 caffeineCache.put(String.valueOf(oldUserInfo.getId()),oldUserInfo);
70 return oldUserInfo;
71 }
72
73 @Override
74 public void deleteById(Integer id) {
75 log.info(“delete”);
76 userInfoMap.remove(id);
77 // 从缓存中删除
78 caffeineCache.asMap().remove(String.valueOf(id));
79 }
80
81}
5、测试的 Controller 类
1import mydlq.club.example.entity.UserInfo;
2import mydlq.club.example.service.UserInfoService;
3import org.springframework.beans.factory.annotation.Autowired;
4import org.springframework.web.bind.annotation.*;
5
6@RestController
7@RequestMapping
8public class UserInfoController {
9
10 @Autowired
11 private UserInfoService userInfoService;
12
13 @GetMapping(“/userInfo/{id}”)
14 public Object getUserInfo(@PathVariable Integer id) {
15 UserInfo userInfo = userInfoService.getByName(id);
16 if (userInfo == null) {
17 return “没有该用户”;
18 }
19 return userInfo;
20 }
21
22 @PostMapping(“/userInfo”)
23 public Object createUserInfo(@RequestBody UserInfo userInfo) {
24 userInfoService.addUserInfo(userInfo);
25 return “SUCCESS”;
26 }
27
28 @PutMapping(“/userInfo”)
29 public Object updateUserInfo(@RequestBody UserInfo userInfo) {
30 UserInfo newUserInfo = userInfoService.updateUserInfo(userInfo);
31 if (newUserInfo == null){
32 return “不存在该用户”;
33 }
34 return newUserInfo;
35 }
36
37 @DeleteMapping(“/userInfo/{id}”)
38 public Object deleteUserInfo(@PathVariable Integer id) {
39 userInfoService.deleteById(id);
40 return “SUCCESS”;
41 }
42
43}
五、SpringBoot 集成 Caffeine 方式二