我正在尝试敲一个api,并在应用程序启动时将数据加载到缓存中。 代码在本地运行,我可以看到缓存在那里,但是当部署在服务器上时,我看到日志可以打印出来进行缓存,但是它没有提供数据。
@Service
@CacheConfig(cacheNames = { "sampleData" })
public class TestService
{
private static final String API = "LInk to some API the data of which need to be cached."
private static final RestTemplate restTemplate = restTemplate();
@Getter
public static Map<String, String> testCountry = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
@Autowired
TestService()
{
}
@PostConstruct
private static void getCountryData()
{
testCountry = TestService.code();
log.info("Caching completed.");
}
public static Map<String, String> code()
{
log.info("Caching is invoked {} ", API);
Map<String, String> map = new TreeMap<>();
try
{
ResponseEntity<SampleCountry[]> responseEntity = restTemplate
.getForEntity(API
, SampleCountry[].class);
List<SampleCountry> SampleCountryList = Arrays.asList(responseEntity.getBody());
map = SampleCountryList.stream()
.collect(Collectors.toMap(SampleCountry::getCode, SampleCountry::getName));
}
catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc)
{
log.error("Error {} ",
httpClientOrServerExc.getStatusCode());
}
return map;
}
@Bean
public static RestTemplate restTemplate()
{
RestTemplate restTemp = new RestTemplate();
((SimpleClientHttpRequestFactory) restTemp.getRequestFactory()).setConnectTimeout(CONNECTION_TIMEOUT);
((SimpleClientHttpRequestFactory) restTemp.getRequestFactory()).setReadTimeout(CONNECTION_TIMEOUT);
return restTemp;
}
}
我正在从另一堂课上调用它。
String countryName = Optional.ofNullable(TestService.testCountry).map(m -> m.get(code))
.orElse(code);
countryName正在从缓存中提取数据。