Redis如何实现在Spring Boot中做缓存?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
1、创建UserService
public interface UserService {
public User findById(int id);
public User create(User user);
public User update(User user);
public void delete(int id);
}
2、创建UserServiceImpl
@Servicepublic class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private UserRedis userRedis;
//this is a key for redis
private static final String keyHead = "mysql:get:user:";
@Override
public User findById(int id) {
User user = userRedis.get(keyHead+id);
if (user == null) {
user = userRepository.findOne(id);
if (user != null) {
userRedis.add(keyHead+id, 30L, user);
}
}
return user;
}
@Override
public User create(User user) {
User newUser = userRepository.save(user);
if (newUser != null) {
userRedis.add(keyHead+newUser.getId(), 30L, newUser);
}
return newUser;
}
@Override
public User update(User user) {
if (user != null) {
userRedis.delete(keyHead+user.getId());
userRedis.add(keyHead+user.getId(), 30L, user);
}
return userRepository.save(user);
}
@Override
public void delete(int id) {
userRedis.delete(keyHead+id);
userRepository.delete(id);
}
}
3、创建UserController
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Object show(@PathVariable int id) {
User user = userService.findById(id);
return user;
}
}
4、结果,在30分钟内只会执行一次查询
关于Redis如何实现在Spring Boot中做缓存问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注天达云行业资讯频道了解更多相关知识。