我想使用Cacheable(sync=true)来控制访问方法的并发行为
@Service
@CacheConfig(cacheNames = "book")
public class BookService {
@Cacheable(key = "#isbn",sync = true)
public Book book(String isbn,int id) {
System.out.println("wait 3s...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Book(isbn, "xxxx");
}
}
编写测试用例:
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
final int index = i;
executorService.execute(new Runnable() {
@Override
public void run() {
bookService.book("1100011", index);
}
});
}
所有键都是相同的,所以同步方法可能有效,但我明白了:
wait 3s...
wait 3s...
wait 3s...
wait 3s...
wait 3s...
这样使用redis缓存是错误的方式吗?
ExecutorService 不知道像 @Cacheable 这样的 Spring Boot 注解,所以这里没有初始化缓存 - 只是简单的方法调用