版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_16855077/article/details/84976991
1.@Cacheable
@Cacheable 作用:把方法的返回值添加到 Ehcache 中做缓存
Value 属性:指定一个 Ehcache 配置文件中的缓存策略,如果么有给定 value,name 则表示使用默认的缓存策略。
一般加在方法上面
1.1 单元测试类
package com.cloudtech.test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.cloudtech.App2;
import com.cloudtech.dao.RoleMapper;
import com.cloudtech.entity.Role;
import com.cloudtech.service.RoleService;
/**
* spring 测试类
* @RunWith:启动器
* SpringJUnit4ClassRunner 让junit和spring环境进行整合
* @SpringBootTest 1.当前类为spring的测试类 2加载spring boot启动类,启动spring boots
*
* @ClassName: RoleTest
* @Description:
* @author wude
* @date 2018年12月12日
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={App2.class})
public class RoleTest {
@Autowired
RoleService roleService;
@Test
public void test1(){
System.out.println("第一次查询:"+roleService.findRoleAll().size());
Role role = new Role();
role.setDescription("test");
role.setName("test");
roleService.addRole(role);
System.out.println("第二次查询:"+roleService.findRoleAll().size());
}
}
1.2 不加缓存,运行test1
不加缓存,第一次是4,跑一个增加语句后,再运行是5,查询的sql有两条
1.3 增加缓存,运行test1
操作行为:先查询再增加,再执行查询。
注意:插入一条数据后,第二次查询结构还是5,而且没有查询语句,说明数据是从缓存中取的,这样缓存和数据库就有不同步的问题。
解决方案:在插入的方法上面增加一个注解,将缓存清空
@Override
@CacheEvict(value="users",allEntries=true)
public int addRole(Role role) {
return roleMapper.insertSelective(role);
}
@Override
@Cacheable(value="users")
public List<Role> findRoleAll() {
return roleMapper.select(null);
}