我想使用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缓存是错误的方法吗?