springboot_cache

使用注解

@EnableCaching(proxyTargetClass = true) //cglib做为代理
@Cacheable

@Cacheable(value = { "sampleCache" },key="targetClass.getName()+'.'+methodName+'.'+#id")//或者key="#id"
public Optional<UserJwtshiro> findById(Long id) {
	TUserJwtshiro tUserJwtshiro = tUserJwtshiroSubMapper.selectByPrimaryKey(id);
	return Optional.ofNullable(tUserJwtshiro).map(userConverter());
}

 注册使用的缓存,springboot不用配制也可以的

import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
public class CacheManagerConfig {
	@Bean
	public CacheManager cacheManager() {
		SimpleCacheManager cacheManager = new SimpleCacheManager();
		cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("sampleCache"),new ConcurrentMapCache("sampleCache2")));
		return cacheManager;
	}
}

与shiro结合时的一些坑

当与shiro结合时有时会发现@Cacheable注解失效
解决方式为所有shiro框架用到的XxxxService.java类
在引入时要这样,必须要有一个@Lazy注解才会好,原因为shiro框架也有一个内置的cache框架
@Autowired
@Lazy

private AuthService authService;

shiro里的AuthRealm.java 或自定义的ShiroFilter等
凡是shiro用到的业务类都要 多加一个@Lazy

猜你喜欢

转载自blog.csdn.net/maqingbin8888/article/details/83149253
今日推荐