我正在使用Spring,我想在启动应用程序之前先缓存一些数据。

我在其他帖子中找到了一些使用@PostConstruct调用我的@Service方法(标注为@Cacheable)的解决方案,例如。 How to load @Cache on startup in spring?
我这样做了,但是在应用程序启动后,我调用了REST端点,该端点再次调用了此服务方法,它再次发送数据库请求(因此尚未缓存)。当我第二次向端点发送请求时,数据被缓存。

结论是,在@PostConstruct上调用Service方法不会导致从数据库缓存数据。

启动应用程序之前是否可以缓存数据?我怎样才能做到这一点?以下是我的代码片段。

@RestController
class MyController {

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

    @Autowired
    MyService service;

    @PostConstruct
    void init() {
        logger.debug("MyController @PostConstruct started");
        MyObject o = service.myMethod("someString");
        logger.debug("@PostConstruct: " + o);
    }

    @GetMapping(value = "api/{param}")
    MyObject myEndpoint(@PathVariable String param) {
        return service.myMethod(param);
    }

}


@Service
@CacheConfig(cacheNames = "myCache")
class MyServiceImpl implements MyService {

    @Autowired
    MyDAO dao;

    @Cacheable(key = "{ #param }")
    @Override
    public MyObject myMethod(String param) {
        return dao.findByParam(param);
    }
}


interface MyService {
    MyObject myMethod(String param);
}


@Repository
interface MyDAO extends JpaRepository<MyObject, Long> {
    MyObject findByParam(String param);
}


@SpringBootApplication
@EnableConfigurationProperties
@EnableCaching
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @Primary
    @Bean
    public CacheManager jdkCacheManager() {
        return new ConcurrentMapCacheManager("myCache");
    }
}

最佳答案

@PostConstruct将适合您的情况。实例化方法bean之后,将调用带有@PostConstruct批注的方法。

但是,如果您依赖于其他bean,并且在应用程序上下文完全启动之后就调用了您的方法?您可以像这样创建一个新的bean:

@Component
public class MyListener
        implements ApplicationListener<ContextRefreshedEvent> {

    public void onApplicationEvent(ContextRefreshedEvent event) {
        //Here call your method of cache
        // Your methode will be called after the application context has fully started
    }
}

关于java - 使用@Cacheable的Spring缓存在启动@PostConstruct时不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41699464/

10-13 04:33
查看更多