java - 在应用程序启动时缓存查找不起作用

标签 java spring tomcat spring-boot spring-cache

我在 Tomcat 9.0.2 上使用 Spring Boot 1.5.9,我正在尝试使用 spring @Cacheable 来缓存查找,该缓存刷新作业在应用程序启动时运行并每 24 小时重复一次如下:

@Component
public class RefreshCacheJob {

    private static final Logger logger = LoggerFactory.getLogger(RefreshCacheJob.class);

    @Autowired
    private CacheService cacheService;

    @Scheduled(fixedRate = 3600000 * 24, initialDelay = 0)
    public void refreshCache() {
        try {
            cacheService.refreshAllCaches();
        } catch (Exception e) {
            logger.error("Exception in RefreshCacheJob", e);
        }
    }

}

缓存服务如下:

@Service
public class CacheService {

    private static final Logger logger = LoggerFactory.getLogger(CacheService.class);

    @Autowired
    private CouponTypeRepository couponTypeRepository;

    @CacheEvict(cacheNames = Constants.CACHE_NAME_COUPONS_TYPES, allEntries = true)
    public void clearCouponsTypesCache() {}

    public void refreshAllCaches() {
        clearCouponsTypesCache();
        List<CouponType> couponTypeList = couponTypeRepository.getCoupons();
        logger.info("######### couponTypeList: " + couponTypeList.size());
    }
}

存储库代码:

public interface CouponTypeRepository extends JpaRepository<CouponType, BigInteger> {
    @Query("from CouponType where active=true and expiryDate > CURRENT_DATE order by priority")
    @Cacheable(cacheNames = Constants.CACHE_NAME_COUPONS_TYPES)
    List<CouponType> getCoupons();
}

稍后在我的网络服务中,当尝试按如下方式获取查找时:

@GET
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Path("/getCoupons")
@ApiOperation(value = "")
public ServiceResponse getCoupons(@HeaderParam("token") String token, @HeaderParam("lang") String lang) throws Exception {
    try {
        List<CouponType> couponsList = couponRepository.getCoupons();
        logger.info("###### couponsList: " + couponsList.size());
        return new ServiceResponse(ErrorCodeEnum.SUCCESS_CODE, resultList, errorCodeRepository, lang);
    } catch (Exception e) {
        logger.error("Exception in getCoupons webservice: ", e);
        return new ServiceResponse(ErrorCodeEnum.SYSTEM_ERROR_CODE, errorCodeRepository, lang);
    }
}

第一次调用它从数据库中获取查找,随后的调用从缓存中获取它,而它应该在 Web 服务中的第一次调用中从缓存中获取它?

为什么我会出现这种行为,我该如何解决?

最佳答案

升级到 Tomcat 9.0.4 后问题已解决

关于java - 在应用程序启动时缓存查找不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48580746/

相关文章:

spring - 如何在 Tomcat 上正确部署基于 Spring 的应用程序?

tomcat - 当我配置 tomcat-user.xml 文件时无法访问 tomcat 中的管理器应用程序

apache-tomcat-6.0.30 套接字绑定(bind)失败/协议(protocol)处理程序启动失败

java - 将 Web 应用程序项目从 eclipse 独立移动到 tomcat

java - 奇怪的谷歌地图尺寸调整行为

java - 如何使用java实时更新带有EditText的TextView

java - XmlBeanFactory 无法加载属性文件作为占位符?

java - Spring 没有匹配类型的 bean,预计至少有 1 个 bean

spring - 是否有任何内置方法可以利用外部服务器的 "tomcat-users.xml"?

Java:泄漏原因未知(非常简单的示例)