Joh*_*ohn 4 caching symfony doctrine-orm
我在我的配置文件中启用了第二级缓存:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
second_level_cache:
region_cache_driver:
type: array
host: ~
port: ~
instance_class: ~
class: ~
id: ~
namespace: ~
cache_provider: ~
region_lock_lifetime: 600
log_enabled: true
region_lifetime: 0
enabled: true
Run Code Online (Sandbox Code Playgroud)
在我需要缓存的实体中,添加新的注释(缓存),如:
/**
* Entity
*
* @ORM\Table(name="entity")
* @ORM\Cache(usage="READ_ONLY", region="entity_cache")
*/
class Entity
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
}
Run Code Online (Sandbox Code Playgroud)
那么,首先什么是缓存命中、缓存未命中和缓存放置?其次,现在发生了什么以及如何缓存我的实体?
首先,这是来自 Doctrine 的一个重要警告:
“二级缓存功能目前被标记为实验性的。这是一个非常复杂的功能,我们还不能保证它在所有情况下都能稳定运行。”
所以,
“如何缓存我的实体?”
在 app/config.yml 中启用第二个 lvl 缓存
doctrine:
orm:
second_level_cache:
enabled: true
Run Code Online (Sandbox Code Playgroud)您还应该为每种类型的数据(实体数据、集合数据或查询数据)指定缓存区域:
regions:
entity_that_rarely_changes:
lifetime: 86400
cache_driver: redis
type: service
id: snc_second_level_cache
Run Code Online (Sandbox Code Playgroud)配置您的实体/实体:
和一个地区(见上文)
/**
* @Cache(usage="READ_ONLY", region="my_entity_region")
*/
class MyEntity
Run Code Online (Sandbox Code Playgroud)最后:您的查询:
$em->persist(new MyEntity($name));
$em->flush();
$em->clear(); // clear em
$item1 = $em->find('MyEntity', 1); // Retrieve item from cache
$item1->setName("newname");
$em->persist($item1);
$em->flush(); // update row and update cache
$em->clear(); // clear em
$item2 = $em->find('MyEntity', 1); // Retrieve item from cache
Run Code Online (Sandbox Code Playgroud)“缓存命中、缓存未命中和缓存放置是什么意思”
您应该检查您的实体缓存区域参数
@Cache(usage="READ_ONLY", region="my_entity_region")
Run Code Online (Sandbox Code Playgroud)
和您的配置 yml 文件,例如:
regions:
my_entity_region:
cache_driver: redis
lifetime: 3600
Run Code Online (Sandbox Code Playgroud)
如果区域(的名称)不同,则实体缓存将始终“丢失”。
我使用了很多外部资源,比如Doctrine 2 文档。你也应该这样做;)
在 Symfony 5.1 上测试,您不需要添加任何包或包。您所要做的就是接近:
# config/packages/dev/cache.yaml
framework:
cache:
app: cache.adapter.redis
default_redis_provider: redis://localhost
Run Code Online (Sandbox Code Playgroud)
# config/packages/dev/doctrine.yaml
doctrine:
orm:
second_level_cache:
enabled: true
region_cache_driver:
type: pool
pool: doctrine.second_level_cache_pool
framework:
cache:
pools:
doctrine.second_level_cache_pool:
adapter: cache.app
Run Code Online (Sandbox Code Playgroud)
例如,在您的实体上:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Cache
*/
class Category { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5690 次 |
| 最近记录: |