1.在整合springboot/shiro/redis 时,发现业务service中@Cacheable注解失效。
2.将Shiro的@Configuration注解去掉,即不用Shiro,@Cacheble可用。
2.本站中看到了类似的帖子,极其类似,但我是在业务Controller中调用的service,并不是在shiro相关代码中,所以有些不知道如何下手。
Redis配置:
@Configuration
@PropertySource("classpath:/redis.properties")
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@SuppressWarnings("rawtypes")
@Bean(name = "cacheManager")
public CacheManager cacheManager(RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
Controller 代码:
@RestController
@RequestMapping("/authority")
public class AuthorityController {
@Autowired
private AuthorityServiceI authorityService;
/**
* 查询单个
* @param authId
* @return
*/
@GetMapping("/{authId}")
@RequiresPermissions("sys:authority")
public Authority getById(@PathVariable(name="authId") String authId) {
return authorityService.selectByPrimaryKey(authId);
}
}
Service 代码:
@Service("authorityService")
@Transactional(readOnly=false, propagation = Propagation.REQUIRES_NEW)
public class AuthorityServiceImpl implements AuthorityServiceI {
@Autowired
private AuthorityMapper authorityMapper;
@Cacheable(value="authority")
@Transactional(readOnly=true)
@Override
public Authority selectByPrimaryKey(String authId) {
return authorityMapper.selectByPrimaryKey(authId);
}
}
大概就是这样。
哈哈,这个问题也困扰我很久。
解决思路是shiro和cache在引用service实例顺序问题,shiro引入应在cache后,
shiro配置文件中引用realm属性bean中引用的service采用延迟加载策略。
@Autowired
@Lazy
private AuthorityServiceI authorityService;