如何注入特定的缓存池?

How to inject a specific cache pool?

在我的 Symfony 5 应用程序中,我想为不同的任务和不同的环境使用不同的缓存。

例如我的配置如下所示:

framework:
    cache:
        pools:
            cache.auth:
                adapter: cache.adapter.redis
                provider: app.my_custom_redis_provider
            cache.sap:
                adapter: cache.adapter.redis
                provider: app.my_custom_redis_provider
services:
    app.my_custom_redis_provider:
        arguments:
            - '%env(REDIS_URL)%'
            -
                retry_interval: 2
                timeout: '%env(REDIS_TIMEOUT)%'
        class: Redis
        factory:
            - Symfony\Component\Cache\Adapter\RedisAdapter
            - createConnection

我在 classes 中使用依赖注入。那么我将如何定义特定的 class 使用这两个缓存池中的哪一个?

目前我的缓存是这样的:

class SapListService implements ListServiceInterface
{
    use LoggerTrait;

    private CountryServiceInterface $countryService;
    private CurrencyServiceInterface $currencyService;

    public function __construct(
        SapClientFactoryInterface $sapClient,
        CacheItemPoolInterface $cache,
        ParameterBagInterface $params
    ) {
        $sapUser = $params->get('sap_user');
        $sapPw = $params->get('sap_pw');
        $urlStruktur = $params->get('sap_struktur');
        $this->countryService = $sapClient->getCountryService($sapUser, $sapPw, $urlStruktur, $cache);
        $this->currencyService = $sapClient->getCurrencyService($sapUser, $sapPw, $urlStruktur, $cache);
    } 

如何配置我的 SapListService 以使用 cache.sap 池?

这在docs上有解释。

Each custom pool becomes a service whose service ID is the name of the pool (e.g. custom_thing.cache). An autowiring alias is also created for each pool using the camel case version of its name - e.g. custom_thing.cache can be injected automatically by naming the argument $customThingCache and type-hinting it with either Symfony\Contracts\Cache\CacheInterface or Psr\Cache\CacheItemPoolInterface:

所以在你的情况下,你可以为以下内容输入提示:

Psr\Cache\CacheItemPoolInterface $cacheSap