三十三 SpringBoot整合@CacheEvict注解使用

 CacheEvict作用:清除缓存

UsersServiceImpl.java

	@Override
	@Cacheable(value="users")
	public List findUserAll() {
		return usersRepository.findAll();
	}

	@Override
	// @CacheEvict(value="users", allEntries=true)表示清除缓存中以users缓存策略缓存中的对象
	@CacheEvict(value="users", allEntries=true)
	public void saveUsers(Users user) {
		usersRepository.save(user);
	}

UsersServiceTest.java

	/**
	 * 1.不加缓存注解,两次查询会查两次,如下:
Hibernate: select users0_.id as id1_3_, users0_.address as address2_3_, users0_.age as age3_3_, users0_.name as name4_3_, users0_.role_id as role_id5_3_ from t_users users0_
[Users [id=1, name=guozi, age=18, address=地球]]
Hibernate: select users0_.id as id1_3_, users0_.address as address2_3_, users0_.age as age3_3_, users0_.name as name4_3_, users0_.role_id as role_id5_3_ from t_users users0_
[Users [id=1, name=guozi, age=18, address=地球]]

	 * 2.开启缓存,在UsersServiceImpl.findUserAll方法上加上@Cacheable(value="users")缓存注解,第二次会从缓存中取数据,如下
Hibernate: select users0_.id as id1_3_, users0_.address as address2_3_, users0_.age as age3_3_, users0_.name as name4_3_, users0_.role_id as role_id5_3_ from t_users users0_
[Users [id=1, name=guozi, age=18, address=地球]]
[Users [id=1, name=guozi, age=18, address=地球]]

	 * 3.在第一次及第二次操作中添加插入数据操作,如添加如下:
		Users users = new Users();
		users.setAddress("山上");
		users.setAge(32);
		users.setName("张三丰");
		this.usersService.saveUsers(users); 
再次执行结果(第二次查询还是从缓存中取,导致第二次查询的数据跟数据库中不同步了):
Hibernate: select users0_.id as id1_3_, users0_.address as address2_3_, users0_.age as age3_3_, users0_.name as name4_3_, users0_.role_id as role_id5_3_ from t_users users0_
[Users [id=1, name=guozi, age=18, address=地球]]
Hibernate: insert into t_users (address, age, name, role_id) values (?, ?, ?, ?)
[Users [id=1, name=guozi, age=18, address=地球]]	

	 * 4.解决如上问题的办法是在保存操作后清空缓存,在UsersServiceImpl.saveUsers方法上添加注解@CacheEvict(value="users", allEntries=true),执行结果如下:
[Users [id=1, name=guozi, age=18, address=地球], Users [id=2, name=张三丰, age=32, address=山上]]
Hibernate: insert into t_users (address, age, name, role_id) values (?, ?, ?, ?)
Hibernate: select users0_.id as id1_3_, users0_.address as address2_3_, users0_.age as age3_3_, users0_.name as name4_3_, users0_.role_id as role_id5_3_ from t_users users0_
[Users [id=1, name=guozi, age=18, address=地球], Users [id=2, name=张三丰, age=32, address=山上], Users [id=3, name=张三丰, age=32, address=山上]]
	 * 
	 * 
	 */
	@Test
	public void testFindUserAll() {
		// 第一次查询
		System.out.println(usersService.findUserAll());
		
		//
		Users users = new Users();
		users.setAddress("山上");
		users.setAge(32);
		users.setName("张三丰");
		this.usersService.saveUsers(users);
		
		// 第二次查询
		System.out.println(usersService.findUserAll());
	}

 

你可能感兴趣的:(SpringBoot)