解决redis注解@Cacheable 不起作用 调用方法不能被保存的问题

时间:2025-04-27 22:11:14

使用@Cacheable 注解可以在redis中 保存,其中 value 是缓存名 ,key是缓存的键可为空,condition是缓存条件可为空。然后将返回的数据作为值存储。

	@GetMapping("/save")
	@Cacheable(value = "merchandise", key = "#id")
	public String saveMerchandise(@RequestParam("id") Integer id){
		return "坎里·德·赫列娜";
	}

但是@Cacheable必须在主方法上,如果想在调用方法中使用,则不会有效,这是因为。

	@GetMapping("/save")
	public String saveMerchandise(Set<Integer> ids){
		if(null != ids && !ids.isEmpty()){
			ids.forEach(x->{
				this.saveRedis(x);
			});
		}
	}

	@Cacheable(value = "merchandise", key = "#id")
	private String saveRedis(Integer id){
		return "坎里·德·赫列娜";
	}

@Cacheable是基于Spring AOP代理类,内部方法调用是不走代理的,@Cacheable是不起作用的

如果想在内部调用方法也能保存,就得用以下方法

1.首先在启动类上加上注解 @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)

@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)

这段代码的作用就是 暴露代理

2.修改类中中调用方的代码

	@GetMapping("/save")
	public String saveMerchandise(Set<Integer> ids){
		if(null != ids && !ids.isEmpty()){
			ids.forEach(x->{
				((当前的类名) AopContext.currentProxy()).saveRedis(x);
			});
		}
	}

	@Cacheable(value = "merchandise", key = "#id")
	private String saveRedis(Integer id){
		return "坎里·德·赫列娜";
	}

3.打开redis,发现有缓存了