@Cacheable
注解的作用:缓存被调用方法的结果(返回值),已经缓存就不再调用注解修饰的方法,适用于查询接口
@RequestMapping("/redisOnly")
@RestController()
public class RedisOnlyController {
@Resource
RedisOnlyService redisOnlyService;
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public User getById(@PathVariable("id") String id) {
return redisOnlyService.selectById(id);
}
}
@Service
public class RedisOnlyServiceImpl implements UserService {
/**
* 先用id生成key,在用这个key查询redis中有无缓存到对应的值
*
* 若无缓存,则执行方法selectById,并把方法返回的值缓存到redis
*
* 若有缓存,则直接把redis缓存的值返回给用户,不执行方法
*/
@Cacheable(cacheNames="user", key="#id")
@Override
public User selectById(String id) {
//直接new一个给定id的用户对象,来返回给用户
return new User(id,"redisOnly","password");
}
}
@CacheEvict
注解简单使用教程——用于删除操作接口
@RequestMapping("/redisOnly")
@RestController()
public class RedisOnlyController {
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public boolean delete(@PathVariable String id) {
return redisOnlyService.delete(id);
}
}
@Service
public class RedisOnlyServiceImpl implements UserService {
@CacheEvict(cacheNames="user", key="#id")
@Override
public boolean delete(String id) {
// 可以在这里添加删除数据库对应用户数据的操作
return true;
}
}
@CachePut
注解简单使用教程—— 更新操作和插入操作
@CachePut
注解的作用同样是缓存被调用方法的结果(返回值),当与@Cacheable
不一样的是:
@CachePut
在值已经被缓存的情况下仍然会执行被@CachePut
注解修饰的方法,而@Cacheable
不会@CachePut
注解适用于更新操作和插入操作
@RequestMapping("/redisOnly")
@RestController()
public class RedisOnlyController {
@Resource
RedisOnlyService redisOnlyService;
@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public User update(@PathVariable String id, @RequestBody User user) {
user.setId(id);
redisOnlyService.update(user);
return user;
}
}
@Service
public class RedisOnlyServiceImpl implements UserService {
// 记录
private AtomicInteger executeCout = new AtomicInteger(0);
@CachePut(cacheNames="user", key="#user.id")
@Override
public User update(User user) {
// 每次方法执行executeCout
user.setUsername("redisOnly" executeCout.incrementAndGet());
// 必须把更新后的用户数据返回,这样才能把它缓存到redis中
return user;
}
}
依赖
代码语言:javascript复制<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置
代码语言:javascript复制spring.cache.type: REDIS
# REDIS (RedisProperties)
spring.redis.database: 0
spring.redis.host: 127.0.0.2
spring.redis.password:
spring.redis.port: 6379
spring.redis.pool.max-idle: 8
spring.redis.pool.min-idle: 0
spring.redis.pool.max-active: 100
spring.redis.pool.max-wait: -1
在启动类添加@EnableCaching
注解开启注解驱动的缓存管理
@Configuration
@EnableAutoConfiguration
@ComponentScan("org.hsweb.demo")
@MapperScan("org.hsweb.demo.dao")
@EnableCaching//开启注解驱动的缓存管理
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
获取缓存值
代码语言:javascript复制@Resource
private CacheManager cacheManager;
Cache cache = cacheManager.getCache(“code”);
String code = (String) cache.get(username).get();