Java spring boot从简单缓存显式获取值
我正在使用Java1.8和SpringBoot:(v2.3.3.RELEASE) 我想实现缓存并使用它的值 基本上 主要类别:Java spring boot从简单缓存显式获取值,java,spring-boot,caching,Java,Spring Boot,Caching,我正在使用Java1.8和SpringBoot:(v2.3.3.RELEASE) 我想实现缓存并使用它的值 基本上 主要类别: @SpringBootApplication @EnableCaching public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } 我的模型/
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
我的模型/实体:
public class RequestConfig {
// attributes
// getter/setter
// constructor
}
我的存储库界面
public interface RequestConfigRepository {
RequestConfig getConfigData();
}
我的存储库实现类:
@Component
@Transactional(readOnly = true)
public class RequestConfigRepositoryImpl implements RequestConfigRepository {
@PersistenceContext
EntityManager entityManager;
@Override
@Cacheable("config")
public RequestConfig getConfigData() {
// DB query to get the details
}
}
我的控制器:
@RestController
public class RequestConfigController {
@Autowired
private RequestConfigRepository requestConfigRepository;
@GetMapping(path = "/config-data")
public RequestConfig getConfigData() {
return requestConfigRepository.getConfigData();
}
}
上述方法效果良好,即首次调用URLhttp://host:port/config-数据进入数据库(获取数据需要一些时间)并返回数据。
接下来,时间向前(非常快)从缓存中获取
现在,在内部,我希望在许多地方(在其他控制器或存储库中)使用这些缓存数据
我必须每次调用getConfigData方法才能使用它?有没有一种方法可以使用cache.get(“key1”)->类似的东西
我尝试使用CacheManager,但无法使用get作为密钥。
例如
所有文档和示例都显示了如何更新缓存、收回/清空缓存等,但无法找到如何从缓存中显式获取键及其值并使用它?嗯,您可能无法确定元素是否已加载到缓存中(或者它可能已被收回)您的其他代码甚至不应该知道缓存存在。因此,只需调用存储库的
getConfigData()
。
@RestController
public class OtherController {
@Autowired
private OtherRepository otherRepository;
@Autowired
private CacheManager cacheManager;
// request mapping, get request, check/transfrom it based on cache loaded earlier.
Some method () {
Cache cache = cacheManager.getCache("config");
// Now how to use this further
}
}