Php 使用redis在symfony2中缓存重复请求
这是我当前的设置:Php 使用redis在symfony2中缓存重复请求,php,symfony,caching,redis,Php,Symfony,Caching,Redis,这是我当前的设置: snc_redis: clients: default: type: predis alias: cache dsn: "redis://127.0.0.1" doctrine: metadata_cache: client: cache entity_manager: default
snc_redis:
clients:
default:
type: predis
alias: cache
dsn: "redis://127.0.0.1"
doctrine:
metadata_cache:
client: cache
entity_manager: default
document_manager: default
result_cache:
client: cache
entity_manager: [bo, aff, fs]
query_cache:
client: cache
entity_manager: default
我有一个API,它可以获取多个重复请求(通常是快速连续的),我可以使用此设置在重复请求时发送回缓存响应吗?还可以设置缓存到期吗?根据您提供的配置示例,我猜您希望缓存条令结果,而不是完整的HTTP响应(尽管后者是可能的,请参见下文) 如果是这样,最简单的方法是,无论何时创建条令查询,都将其设置为使用您在上面设置的使用redis的
$qb = $em->createQueryBuilder();
// do query things
$query = $qb->getQuery();
$query->useResultCache(true, 3600, 'my_cache_id');
这将使用缓存ID将该查询的结果缓存一小时。清除缓存有点麻烦:
$cache = $em->getConfiguration()->getResultCacheImpl();
$cache->delete('my_cache_id');
若你们想缓存完整的响应,也就是说,你们在应用程序中做一些需要很长时间的处理,那个么有很多方法可以做到这一点。可以将其序列化并弹出到redis中:
$myResults = $service->getLongRunningResults();
$serialized = serialize($myResults);
$redisClient = $container->get('snc_redis.default');
$redisClient->setex('my_id', $serialized, 3600);
或者,研究专用HTTP缓存解决方案,如或参阅
编辑:SncRedisBundle提供了自己版本的条令缓存提供者。因此,在您的答案中,您创建了自己的类,您也可以这样做:
my_cache_service:
class: Snc\RedixBundle\Doctrine\Cache\RedisCache
calls:
- [ setRedis, [ @snc_redis.default ] ]
这几乎和你们班正在做的一样。因此,您不必使用
$app\u cache->get('id')
而是使用$app\u cache->fetch('id')
。通过这种方式,您可以切换出缓存的后端,而无需更改应用程序类,只需更改服务描述。最后,我创建了一个缓存管理器,并将其注册为名为@app\u cache的服务
use Predis;
class CacheManager
{
protected $cache;
function __construct()
{
$this->client = new Predis\Client();
}
/**
* @return Predis\Client
*/
public function getInstance()
{
return $this->client;
}
}
在控制器中,我可以md5请求uri
$id = md5($request->getRequestUri());
如果返回$result
if($result = $app_cache->get($id)) {
return $result;
}
如果它不起作用…不管怎样…并将响应保存到下次
$app_cache->set($id,$response);
要设置到期时间,请使用第三个和第四个参数ex
=秒和px
=毫秒
$app_cache->set($id,$response,'ex',3600);
您是在运行API(即,您希望缓存对接收到的请求的响应)还是从API请求数据(即,您希望缓存来自该API的响应)?我正在运行API,我希望缓存响应Sah,我知道您现在得到了什么。我已经用一个可能更好的解决方案更新了我的答案。