spring-boot-starter-data-redis Cacheable(sync=true) 看起来不起作用?

问题描述 投票:0回答:1

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

spring spring-boot spring-data-redis
1个回答
0
投票

ExecutorService 不知道像 @Cacheable 这样的 Spring Boot 注解,所以这里没有初始化缓存 - 只是简单的方法调用

© www.soinside.com 2019 - 2024. All rights reserved.