IAdminServiceImpl.java
2.1 KB
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
package com.it.service.impl;
import com.it.mapper.adminMapper;
import com.it.entity.admin;
import com.it.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class IAdminServiceImpl implements IAdminService {
public static final String CACHE_KEY_USER = "user:";
@Autowired
private adminMapper adminMapper;
@Autowired
private RedisTemplate redisTemplate;
@Override
public Boolean save(admin admin) {
//1 先插入mysql并成功
int i = adminMapper.insert(admin);
if(i > 0)
{
//2 需要再次查询一下mysql将数据捞回来并ok
admin = adminMapper.selectById(admin.getUserid());
//3 将捞出来的user存进redis,完成新增功能的数据一致性。
String key = CACHE_KEY_USER+admin.getUserid();
redisTemplate.opsForValue().set(key,admin);
}
// 插入删除等操作返回的都是影响行数,即是数字。那么则大于0为真,其他情况为假
return true;
}
@Override
public admin getById(Integer id) {
admin ad = null;
String key = CACHE_KEY_USER+id;
//1 先从redis里面查询,如果有直接返回结果,如果没有再去查询mysql
ad = (admin) redisTemplate.opsForValue().get(key);
System.out.println(ad);
if (ad == null){
//2 redis里面无,继续查询mysql
ad = adminMapper.selectById(id);
if (ad == null){
//3.1 redis+mysql 都无数据
//你具体细化,防止多次穿透,我们规定,记录下导致穿透的这个key回写redis
return ad;
}else {
//3.2 mysql有,需要将数据写回redis,保证下一次的缓存命中率
redisTemplate.opsForValue().set(key,ad);
}
}
return ad;
}
@Override
public List<admin> getAll() {
return adminMapper.selectList(null);
}
}