springboot-mybatits数据库,ecache缓存操作,批量操作,事物操作
文章目录
代码下载: https://github.com/2010yhh/springBoot-demos/tree/master/springboot-static
环境
idea2018,jdk1.8,
springboot版本:1.5.9.RELEASE
1.mybatits,数据库ecache缓存操作
ecache配置:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="shiroCache">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<!-- 表示此缓存最多可以存活2分钟,如果期间超过1分钟未访问 那么此缓存失效-->
<cache name="user"
maxEntriesLocalHeap="2000"
eternal="false"
timeToIdleSeconds="60"
timeToLiveSeconds="120"
overflowToDisk="false"
statistics="true">
</cache>
</ehcache>
使用:
@Service
@CacheConfig(cacheNames = {"user"})
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Cacheable(key = "#userName")
@Override
public List<User> findByUserName(String userName, String passWord) {
UserExample example = new UserExample();
example.createCriteria().andUserNameEqualTo(userName).andPassWordEqualTo(passWord);
return userMapper.selectByExample(example);
}
@CachePut(key = "#user.userId")
@Override
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void addUser(User user) {
//测试事物特性
userMapper.insertSelective(user);
//userMapper.insertSelective(user);
}
}
测试时,设置缓存30s,(timeToIdleSeconds=“30”
timeToLiveSeconds=“30”)在缓存有效期内查询:从日志可看出,只查询数据库一次。