spring boot mybatis redis缓存

使用场景: 集群环境,不能使用JVM缓存,改用redis缓存

pom

      <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

application.properties

# redis连接配置
spring.redis.host= localhost
spring.redis.port= 6379
spring.redis.password=
spring.redis.timeout=43200

# cache
spring.cache.type=redis

dao

@CacheConfig(cacheNames="dictDtlCache")
class DictDao
{
		@Cacheable(key = "T(String).valueOf(#strSn) + ':' +T(String).valueOf(#key)")
	public DictionaryDtl findOneByDictSnAndKey(String strSn, String key)
	{
		Map<String, Object> map = new HashMap<>();
		map.put("strSn", strSn);
		map.put("key", key);
		return sqlsession.selectOne("DictionaryDtlDao.findOneByDictSnAndKey", map);
	}

	/**
	 * @description 默认一级字典strSn存在,二级字典可以不存在
	 * @author zhuxiang
	 * @date 13:46 2020/7/9
	 * @param: strSn
	 * @param: key
	 * @param: value
	 * @return int
	 **/
	@CachePut(key = "T(String).valueOf(#strSn) + ':' +T(String).valueOf(#key)")
	public DictionaryDtl setValueByDictSnAndKey(String strSn, String key, String value)
	{
		Map<String, Object> map = new HashMap<>();
		map.put("strSn", strSn);
		map.put("key", key);
		map.put("value", value);
		if (findOneByDictSnAndKey(strSn, key) == null)
		{
			map.put("id", UUIDUtil.getUUID());
			map.put("username", "admin");
			map.put("sysdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			sqlsession.insert("DictionaryDtlDao.insertValueByDictSnAndKey", map);
		}
		sqlsession.update("DictionaryDtlDao.updateValueByDictSnAndKey", map);
		return findOneByDictSnAndKey(strSn, key);
	}
}
posted @ 2020-07-09 20:30  fight139  阅读(183)  评论(0编辑  收藏  举报