《springboot学习》十五 @Cacheable 与@CacheEvict

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);
	}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值