1.首先介绍项目启动时缓存数据库数据到redis(以缓存用户表数据为例)
1.1.创建UserCache类
/** *@Description 用户缓存 *@param *@return *@author wang hq */ @Component public class UserCache { @Autowired private RedisService redisService; @Autowired private UserDao userDao; private static UserCache userCache; @PostConstruct public void init() { userCache = this; userCache.redisService = this.redisService; userCache.userDao = this.userDao; } /** * @param userDtos * @return * @将数据库查询出来的数据 进行格式化 并存入 map和redis */ public static void init(List<UserDto> userDtos) { userCache.redisService.del(Constant.REDIS_USER); for (UserDto userDto : userDtos) { userCache.redisService.hSet(Constant.REDIS_USER, String.valueOf(userDto.getId()), userDto); } } /** * @param id * @param value * @修改缓存中的数据 */ public static void modify(Integer id, UserDto value) { if (value == null && id == null) { new Throwable("id and value is not null!"); } //修改 userCache.redisService.hSet(Constant.REDIS_USER, String.valueOf(id), value); } /** * @param id * @删除缓存中的数据 */ public static void delete(Integer id) { if (id == null) { new Throwable("id is not null!"); } userCache.redisService.hDel(Constant.REDIS_USER, String.valueOf(id)); } /** * @param users * @删除缓存中的数据 */ public static void deleteList(List<Integer> users) { if (users == null) { new Throwable("id is not null!"); } for (Integer id : users) { userCache.redisService.hDel(Constant.REDIS_USER, String.valueOf(id)); } } /** * @param id * @return * @从缓存中获取appid对应的value */ public static UserDto userDto(Integer id) { if (id != null) { new Throwable("id is not null!"); } if (userCache.redisService.hGet(Constant.REDIS_USER, String.valueOf(id)) != null) { return JSONObject.parseObject(JSONObject.toJSONString(userCache.redisService.hGet(Constant.REDIS_USER, String.valueOf(id))), UserDto.class); } UserDto userDto = new UserDto(); userDto.setId(id); userDto = userCache.userDao.findOne(userDto, null); modify(id, userDto); return userDto; } }
1.2.创建DemoRunner
@Order(3) @Component public class DemoRunner implements ApplicationRunner { @Autowired private UserDao userDao; @Override public void run(ApplicationArguments applicationArguments) throws Exception { UserCache.init(userDao.findAll(new User(), null)); } }
到这里后启动项目会发现用户数据已缓存到Redis表中
若是做了上面操作后报RedisService注入错误的问题时 可参考
https://blog.csdn.net/weixin_45735355/article/details/118308909?spm=1001.2014.3001.5501即可解决
2.CRUD操作时同步到Redis缓存
2.1 插入
Integer flag = userDao.save(user); if (flag > 0) { UserCache.modify(user.getId(), JSONObject.parseObject(JSONObject.toJSONString(user), UserDto.class)); }
2.2 删除
Integer flag = userDao.delete(user); if (flag > 0) { UserCache.delete(user.getId()); } return flag;
更新
Integer flag = userDao.update(user); if (flag > 0) { TypeDictCache.modify(user.getId(), JSONObject.parseObject(JSONObject.toJSONString(user), UserDto.class)); } return flag;
