dubbo中接口cache使用及原理

发布时间 2023-12-01 22:52:53作者: 使用D

服务提供者类增加注解@DubboService(cache = "true")

指定服务调用的缓存实现,包括:lru, threadlocal, jcache。

 提供者

@DubboService(token = "true", cache = "true")
public class CacheServiceImpl implements CacheService {

    private final AtomicInteger i = new AtomicInteger();

    public String findCache(String id) {
        return "request: " + id + ", response: " + i.getAndIncrement();
    }

}

消费者

@DubboReference(cache = "true")
private CacheService service;

public void findCache() {
    service.findCache("0");
}

dubbo缓存module

 <dependency>
      <groupId>org.apache.dubbo</groupId>
      <artifactId>dubbo-filter-cache</artifactId>
      <version>${project.parent.version}</version>
    </dependency>

核心缓存filter:org.apache.dubbo.cache.filter.CacheFilter

public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (cacheFactory == null
            || ConfigUtils.isEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) {
        return invoker.invoke(invocation);
    }
    Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation);
    if (cache == null) {
        return invoker.invoke(invocation);
    }
    String key = StringUtils.toArgumentString(invocation.getArguments());
    Object value = cache.get(key);
    return (value != null)
            ? onCacheValuePresent(invocation, value)
            : onCacheValueNotPresent(invoker, invocation, cache, key);
}