[英]What is a right Spring Cache Configuration for Java Map and its values?
我有下一個服務,它返回整個地圖和一個鍵的值。
@Service
@CacheConfig(cacheNames = "messages")
public class MessageService {
private final MessageRepository messageRepository;
@Autowired
public MessageService(MessageRepository messageRepository) {
this.messageRepository = messageRepository;
}
@Cacheable
public Map<String, String> findMessages() {
return messageRepository.findAll();
}
@Cacheable(key = "#key")
public String getMessage(String key) {
return messageRepository.findByKey(key);
}
}
當調用findMessages()
方法時,我想保存緩存中的所有消息。 當調用getMessage(String key)
時,它應該從緩存中返回一個值,但不是從存儲庫中返回。 是否可以使用Spring注釋來做到這一點? 目前,它為這兩種方法分別設置了緩存條目。
當您將方法分成不同的服務(公共外觀)時,它可以正常工作。
從spring-caching示例 ( /complete
)開始,我通過對新類(應該是“緩存服務”)的小調整移動了SimpleBookRepository
:
@Component
public class SimpleCache {
@Cacheable("map")
public Map<String, String> getMap() {
simulateSlowService();
Map<String, String> result = new HashMap<>();
result.put("foo", "bar");
result.put("bar", "foo");
return result;
}
// Don't do this at home
private void simulateSlowService() {
try {
long time = 3000L;
Thread.sleep(time);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
一些小調整以匹配問題/示例:
package hello;
public interface BookRepository {
//originally it returned {@link hello.Book}
String getByIsbn(String isbn);
}
...並介紹(作為緩存外觀/調用者......在緩存getByIsbn()
沒有意義!!):
@Component
public class SimpleBookRepository implements BookRepository {
@Autowired
private transient SimpleCache cache;
@Override
public String getByIsbn(String isbn) {
return cache.getMap().get(isbn);
}
}
使用稍微調整的AppRunner
:
//...
logger.info(".... Fetching books");
logger.info("foo --> {}", bookRepository.getByIsbn("foo"));
logger.info("bar --> {}", bookRepository.getByIsbn("bar"));
logger.info("foo --> {}", bookRepository.getByIsbn("foo"));
logger.info("bar --> {}", bookRepository.getByIsbn("bar"));
logger.info("foo --> {}", bookRepository.getByIsbn("foo"));
logger.info("foo --> {}", bookRepository.getByIsbn("foo"));
//...
...我們得到以下輸出:
2017-06-30 15:54:52.584 INFO 3984 --- [ main] hello.AppRunner : .... Fetching books
2017-06-30 15:54:55.616 INFO 3984 --- [ main] hello.AppRunner : foo --> bar
2017-06-30 15:54:55.618 INFO 3984 --- [ main] hello.AppRunner : bar --> foo
2017-06-30 15:54:55.619 INFO 3984 --- [ main] hello.AppRunner : foo --> bar
2017-06-30 15:54:55.619 INFO 3984 --- [ main] hello.AppRunner : bar --> foo
2017-06-30 15:54:55.619 INFO 3984 --- [ main] hello.AppRunner : foo --> bar
2017-06-30 15:54:55.619 INFO 3984 --- [ main] hello.AppRunner : foo --> bar
2017-06-30 15:54:55.623 INFO 3984 --- [ main] hello.Application : Started Application in 4.982 seconds (JVM running for 5.513)
;)
你能做點什么嗎?
public String getMessage(String key) {
return findMessages().get(key)
}
我認為您不需要使用@Cacheable來注釋getMessage,因為您正在訪問已經緩存的findMessages()。
啊@ xerx593打賭我:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.