Spring Boot 使用 Redis 做缓存
2016-12-29 本文已影响361人
就怕是个demo
这里有两种方式
- 使用注解方式(但是小爷不喜欢)
- 直接《Spring Boot 使用 Redis》中的redisTemplate
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分钟内只会执行一次查询
Paste_Image.png