SpringBoot之Mybatis操作中使用Redis做緩存
轉自:http://www.cnblogs.com/5ishare/
今天這篇博客學習下Mybatis操作中使用Redis做緩存。這里其實主要學習幾個注解:@CachePut、@Cacheable、@CacheEvict、@CacheConfig。
一、基礎知識
@Cacheable
@Cacheable 的作用 主要針對方法配置,能夠根據方法的請求參數對其結果進行緩存
參數 | 解釋 | example |
---|---|---|
value | 緩存的名稱,在 spring 配置文件中定義,必須指定至少一個 | 例如: @Cacheable(value=”mycache”) @Cacheable(value={”cache1”,”cache2”} |
key | 緩存的 key,可以為空,如果指定要按照 SpEL 表達式編寫,如果不指定,則缺省按照方法的所有參數進行組合 | @Cacheable(value=”testcache”,key=”#userName”) |
condition | 緩存的條件,可以為空,使用 SpEL 編寫,返回 true 或者 false,只有為 true 才進行緩存 | @Cacheable(value=”testcache”,condition=”#userName.length()>2”) |
@CachePut
@CachePut 的作用 主要針對方法配置,能夠根據方法的返回值對其結果進行緩存,和 @Cacheable 不同的是,它每次都會觸發真實方法的調用,在其他地方寫的是根據方法的請求參數對其結果進行緩存,實際是按方法返回值進行緩存的,這里我就遇到了一個坑,我開始的時候是在Mybatis的Mapper層進行緩存的,如下面的代碼。但是緩存到Redis的是Null值,今天看了一博友的博客,交流了一下,才知道它緩存的是方法的返回值,如果把下面update的返回值該為int,在redis中保存的是int類型,報的錯誤是int無法轉換成User對象。
@CachePut(value="user",key = "#p0.id") @Update({"UPDATE user SET name=#{name},age=#{age} WHERE id =#{id}"}) void update(User user);
參數 | 解釋 | example |
---|---|---|
value | 緩存的名稱,在 spring 配置文件中定義,必須指定至少一個 | @CachePut(value=”my cache”) |
key | 緩存的 key,可以為空,如果指定要按照 SpEL 表達式編寫,如果不指定,則缺省按照方法的所有參數進行組合 | @CachePut(value=”testcache”,key=”#userName”) |
condition | 緩存的條件,可以為空,使用 SpEL 編寫,返回 true 或者 false,只有為 true 才進行緩存 | @CachePut(value=”testcache”,condition=”#userName.length()>2”) |
@CachEvict
@CachEvict 的作用 主要針對方法配置,能夠根據一定的條件對緩存進行清空
參數 | 解釋 | example |
---|---|---|
value | 緩存的名稱,在 spring 配置文件中定義,必須指定至少一個 | @CacheEvict(value=”my cache”) |
key | 緩存的 key,可以為空,如果指定要按照 SpEL 表達式編寫,如果不指定,則缺省按照方法的所有參數進行組合 | @CacheEvict(value=”testcache”,key=”#userName”) |
condition | 緩存的條件,可以為空,使用 SpEL 編寫,返回 true 或者 false,只有為 true 才進行緩存 | @CacheEvict(value=”testcache”,condition=”#userName.length()>2”) |
allEntries | 是否清空所有緩存內容,缺省為 false,如果指定為 true,則方法調用后將立即清空所有緩存 | @CachEvict(value=”testcache”,allEntries=true) |
beforeInvocation | 是否在方法執行前就清空,缺省為 false,如果指定為 true,則在方法還沒有執行的時候就清空緩存,缺省情況下,如果方法執行拋出異常,則不會清空緩存 | @CachEvict(value=”testcache”,beforeInvocation=true) |
@CacheConfig
所有的@Cacheable()里面都有一個value=“xxx”的屬性,這顯然如果方法多了,寫起來也是挺累的,如果可以一次性聲明完 那就省事了,有了@CacheConfig這個配置,@CacheConfig is a class-level annotation that allows to share the cache names,如果你在你的方法寫別的名字,那么依然以方法的名字為准。
二、實例
還是在上一博客demo的基礎上進行修改,原本是在Mybatis的Mapper層上增加cache注解,但由於update返回值為void,所以這里又增加了一services層,mapper層算是DAO層。這里使用了@CacheConfig注解指定類級別的value屬性,如果在方法上定義就以方法為主,就近原則。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
package
com.example.services;
import
java.util.List;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.cache.annotation.CacheConfig;
import
org.springframework.cache.annotation.CacheEvict;
import
org.springframework.cache.annotation.CachePut;
import
org.springframework.cache.annotation.Cacheable;
import
org.springframework.stereotype.Service;
import
com.example.model.User;
import
com.example.write.mapper.WriteUserMapper;
@Service
@CacheConfig
(cacheNames=
"user"
)
public
class
UserServices {
@Autowired
private
WriteUserMapper writeUserMapper;
public
List<User> getAll()
{
return
writeUserMapper.getAll();
}
@Cacheable
(key =
"#p0"
)
public
User getOne(String id)
{
return
writeUserMapper.getOne(id);
}
public
void
insert(User user)
{
writeUserMapper.insert(user);
}
@CachePut
(value=
"user"
,key =
"#p0.id"
)
public
User update(User user)
{
writeUserMapper.update(user);
return
user;
}
@CacheEvict
(value=
"user"
,key =
"#p0"
,allEntries=
true
)
public
void
delete(String id)
{
writeUserMapper.delete(id);
}
}
|
UserController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
package
com.example.demo;
import
java.io.Serializable;
import
java.util.List;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.data.redis.core.RedisTemplate;
import
org.springframework.data.redis.core.StringRedisTemplate;
import
org.springframework.stereotype.Controller;
import
org.springframework.ui.Model;
import
org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.servlet.ModelAndView;
import
com.example.model.User;
import
com.example.model.UserSexEnum;
import
com.example.read.mapper.ReadUserMapper;
import
com.example.services.UserServices;
import
com.example.write.mapper.WriteUserMapper;
import
io.lettuce.core.dynamic.annotation.Param;
@Controller
@RequestMapping
(
"/user"
)
public
class
UserController {
@Autowired
private
WriteUserMapper userMapperWrite;
@Autowired
private
ReadUserMapper userMapperRead;
@Autowired
private
StringRedisTemplate stringRedisTemplate;
@Autowired
private
RedisTemplate<String, Serializable> redisCacheTemplate;
@Autowired
private
UserServices userServices;
@RequestMapping
(value =
"/alluser.do"
,method = RequestMethod.GET)
public
String getallusers(Model model) {
List<User> users=userServices.getAll();
model.addAttribute(
"users"
, users);
// stringRedisTemplate.opsForValue().set("keytest", "cuiyw");
// final String keytest = stringRedisTemplate.opsForValue().get("keytest");
// model.addAttribute("keytest", keytest);
// String key = "1857XXXX040";
// redisCacheTemplate.opsForValue().set(key, new User(key, "cuiyw", 18, UserSexEnum.MAN));
// // TODO 對應 String(字符串)
// final User user = (User) redisCacheTemplate.opsForValue().get(key);
// model.addAttribute("user", user);
return
"userlist"
;
}
@RequestMapping
(value =
"/insert.do"
,method = RequestMethod.GET)
public
String adduser(Model model) {
User user=
new
User();
user.setName(
"cuiyw"
);
user.setAge(
27
);
userServices.insert(user);
// List<User> users=userMapperWrite.getAll();
// model.addAttribute("users", users);
return
"forward:/user/alluser.do"
;
}
@RequestMapping
(value =
"/getuserbyid.do/{id}"
,method = RequestMethod.GET)
public
ModelAndView GetUserById(
@PathVariable
(
"id"
) String id) {
System.out.println(id);
User user=userServices.getOne(id);
System.out.println(user.toString());
ModelAndView modelAndView =
new
ModelAndView(
"userlist"
);
modelAndView.addObject(
"user"
, user);
return
modelAndView;
}
@RequestMapping
(value =
"/deleteuserbyid.do/{id}"
,method = RequestMethod.GET)
public
String DeleteUserById(
@PathVariable
(
"id"
) String id) {
userServices.delete(id);
return
"forward:/user/alluser.do"
;
}
@RequestMapping
(value =
"/updateuserbyid.do/{id}"
,method = RequestMethod.GET)
public
String UpdateUserByid(
@PathVariable
(
"id"
) String id) {
User user=userServices.getOne(id);
System.out.println(user.toString());
user.setAge(
28
);
System.out.println(user.toString());
userServices.update(user);
System.out.println(user.toString());
return
"forward:/user/alluser.do"
;
}
}
|
這里先輸入http://localhost:8080/user/getuserbyid.do/17通過getOne()方法在redis中緩存一個user。通過redis-cli可以看到user::17已在redis中。
然后通過update()方法輸入http://localhost:8080/user/updateuserbyid.do/17修改user,此時年齡改為了28,數據庫的值也會變了。然后多次使用http://localhost:8080/user/updateuserbyid.do/17這個url刷新瀏覽器,此時是不會報錯的,如果是在mapper中使用@Cacheput時由於保存的是null就會導致報錯。
最后通過delete()方法輸入http://localhost:8080/user/deleteuserbyid.do/17刪除redis和數據庫中的user對象.
至此,基本把這4個注解大致了解了一下,這里還有一個地方需要補充,就是如果按照上面運行還是不行的,它依然找不到UserServices,在UserController中找不到這個類,還需要在main方法上面@ComponentScan注解加上掃描com.example.services。
@ComponentScan(basePackages={"com.example.config","com.example.demo","com.example.services"})
最后來一碗雞湯,記錄下今天看抖音聽到的一句話,還挺有道理。
為什么大多數人寧願吃生活的苦,而不願意吃學習的苦?因為學習的苦需要自己主動去吃,而生活的苦你躺着它就來了。