同一個類裏@Cacheable緩存不起作用

一、問題描述

環境:

  • springboot 2.1.2.RELEASE
  • ehcache 2.10.6

如下,selectAll()方法通過@Cacheable設置了緩存,在get(String paramKey)方法裏面,調用selectAll()時不會使用緩存。但其他類調用selectAll()方法時,緩存有效。


@Service
public class SystemConfigService{
	@Autowired
	private SystemConfigMapper systemConfigMapper;

	public SystemConfig get(String paramKey) {
		//此處調用selectAll方法,selectAll方法不會使用緩存
		List<SystemConfig> list =selectAll();
		
	}

	@Cacheable(cacheNames = "dict")
	public List<SystemConfig> selectAll() {
		return systemConfigMapper.selectAll();
	}
}

二、參考解決方法

問題原因:

註解@Cacheable是使用AOP代理實現的 ,通過創建內部類來代理緩存方法,類內部的方法調用類內部的緩存方法不會走代理,所以就不能正常創建緩存,所以每次都需要去調用數據庫。

參考解決方法:

方法1:將緩存的方法單獨放一個類裏,與調用的方法分開,不放在同一個類裏。
方法2:從ApplicationContext裏獲取當前類的代理對象。

方法1不貼代碼了,方法2參考代碼如下:


@Service
public class SystemConfigService{
	@Autowired
	private SystemConfigMapper systemConfigMapper;
	//注入當前對象的代理對象
	@Autowired
	private SystemConfigService _this;


	public SystemConfig get(String paramKey) {
		//通過代理對象訪問方法
		List<SystemConfig> list = _this.selectAll();
	}

	@Cacheable(cacheNames = CacheConstant.ONE_HOUR)
	public List<SystemConfig> selectAll() {
		return systemConfigMapper.selectAll();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章