고급 프로그래밍: 캐시를 사용합니다.
고급 프로그래밍: 캐시를 사용합니다.
다음 예를 봅시다.우리는 두 개의 표, 국가와 도시가 있는데, 그것들은 관련이 있다
select * from countries
inner join cities on countries.idcountry=cities.idcities
결과를 캐시하려고 합니다.우리의 동기는 무엇입니까?
우리의 동기는 데이터베이스에 대한 가장 빠른 조회가 실행되지 않은 조회이기 때문이다.
이런 상황에서 우리는 정보를 한 번 캐시해서 메모리에 저장하고 여러 번 사용하기를 바란다.따라서 우리는 여러 차례 같은 데이터를 사용할 수 있지만, 우리는 데이터베이스를 한 번만 조회했다.그러나 우리는 데이터베이스에도 자신의 캐시가 있다는 것을 고려해야 한다. 그러나 데이터베이스는 우리가 관리하는 것이 아니기 때문에 캐시가 무엇인지, 언제 어디서, 보통 자동으로 갱신되는지 모른다.

캐시가 잘못되었습니다.
캐시의 주요 문제는 실효이다.
예를 들어, 만약 우리가 캐시 조회를 한다면?
select * from countries; -- 100 countries
나중에 우리는 새로운 국가 (예를 들어 남수단) 를 추가하기로 결정했다.그러나 우리의 캐시는 새로운 나라가 있는지 모르기 때문에 전체 캐시를 효력을 상실해야 한다.select * from countries; -- 100 countries (from cache)
-- we invalidate the cache
select * from countries; -- 101 countries (from the database)
ID를 통한 무효화

이런 무효 형식은 특정 조회를 무효화시킨다.그러나 어떤 캐시를 실효시키는지 알아야 하기 때문에 수동으로 실효시키려면 비현실적이다.그것은 통상적으로 내부에서 사용된다.
이거 어떻게 하는 거예요?
select * from countries;
우리는 조회를 ID로 사용할 수 있지만, 이것은 비현실적이다.반대로, 우리는 해시를 생성할 수 있다(예를 들어sha256)저희 신분증이에요.
286c960d1c9c21e84df5a263bddcd2771da976fa306cfdb3fdea60e174a680a8
비록 그것은 결코 짧지 않지만, 항상 같은 길이를 가지고 있으며, 조회가 길거나 더 복잡해도 키로 사용할 수 있다.하지만 조회에 파라미터가 있다면?
select * from countries where idcountry=?;
그리고 파라미터를 저장하고 산열을 생성합니다. 파라미터를 포함합니다.따라서, 우리의 해시는 조회의 모든 정보를 포함한다: 조회와 파라미터 (있다면)그렇다면
select * from countries; -- it reads from the database and store in the cache
-- here we invalidate the cache id 286c960d1c9c21e84df5a263bddcd2771da976fa306cfdb3fdea60e174a680a8
select * from countries; -- since the cache is gone, then it reads again from the database and store in the cache
TTL을 통한 생존 시간 실효
캐시를 올바르게 만드는 방법 중 하나는 TTL을 통해서입니다.따라서 우리의 캐시는 만기일이 있다.그것은 약간의 장점과 결점이 있다.
select * from countries; -- we store it for (example) 5 seconds
-- (we wait 3 seconds)
select * from countries; -- it reads from the cache that it is still alive
-- (we wait another 3 seconds)
select * from countries; -- it reads from the database because the cache expired.
via 가족 또는 그룹 무효

또 다른 캐시를 무효화하는 방법은 캐시 족이나 캐시 그룹을 통해서입니다.
select * from countries; -- stored in the family called "countries"
-- countries=['select * from countries']
화목하다select * from countries where idcountry=56; -- also stored in the family called "countries"
-- countries=['select * from countries','select * from countries where idcountry=56']
그리고 우리는 새로운 국가를 추가하기로 결정했다. 그러면 우리는 전체 가족의'국가'를 무효로 할 수 있고, 이 가족의 국가는 두 개의 조회를 모두 무효로 할 수 있다.그러나
이것은 우리의 초기 조회다.
select * from countries
inner join cities on countries.idcountry=cities.idcities
이 문제는 아마도 두 가정, 국가, 도시에 달려 있을 것이다.따라서 만약 우리가 새로운 국가나 새로운 도시를 추가한다면, 이 조회는 두 가족 때문에 무효가 될 수 있다.실시
우리는 두 개의 라이브러리를 사용할 것이다.
EFTEC/PdoOne: Pdo One (github.com)
EFTEC/CacheOne: CacheOne is a cache of service for php (github.com)
수동으로 또는 composer를 통해 추가할 수 있습니다.
composer require eftec/pdoone
composer require eftec/cacheone
CacheOne은 Redis(권장), PHP 확장 APCU, Memcache 또는 파일 시스템과 함께 사용됩니다.데이터베이스 및 캐시 시스템에 연결
// You must add the libraries prior to be used
$cache=new CacheOne('redis',127.0.0.1,'redistest',6379); // if you don't have redis, then you could use any other.
$cache->setSerializer('json-object'); // the information is stored as json-object.
$pdoOne=new PdoOne('mysql',127.0.0.1,'root','abc.123','dbtest');
$pdoOne->setCacheService($cache); // di
$pdoOne->open(); // open database
캐시 정보
$countries=$pdoOne->useCache(3600)
->select('*')
->from('countries')
->toList(); // cache lasts 1 hour
$countries=$pdoOne->useCache(3600,'countries')
->select('*')
->from('countries')
->toList(); // cache lasts 1 hour or until the family of cache "countries" is purged.
$countries=$pdoOne->useCache(3600,'*') // indicates to use as family the table indicated in methods from() and joins().
->select('*')
->from('countries')
->toList(); // cache lasts 1 hour or until the family of cache "countries" is purged.
$countries=$pdoOne->useCache(3600,'*') // indicates to use as family the table indicated in methods from() and joins().
->select('*')
->from('countries')
->innerjoin('cities on countries.idcountry=cities.idcountry')
->toList(); // cache lasts 1 hour or until the family of cache "countries" or "cities" is purged.
캐시를 올바르게 만드는 중
우리는 두 가지 방법으로 캐시를 무효화시킬 수 있습니다. invalidateCache () 방법으로 캐시를 무효화시킬 수 있습니다. 그 중에서 우리는 ID나 일련의 캐시를 통해 캐시를 무효화시킬 수 있습니다.
두 번째 방법은 캐시를 사용하여 DML 작업(삽입, 업데이트 및 제거)을 실행하는 것입니다.캐시 패밀리가 자동으로 지워집니다.
$pdoOne->invalidateGroup('','countries'); // we invalidate all the cache of the family countries
// or we could invalidate for insert,update or delete
$pdoOne->useCache(3600,'*')->from("countries")->set(['idcountry,name'],[101,'South Sudan'])->insert();
PSR-6
PSR-6 표준을 따르지 않는 이유는 무엇입니까?
select * from countries
inner join cities on countries.idcountry=cities.idcities
PSR-6에서 캐시를 다음으로 저장할 수 있습니다.$result=[..]; // storing the result of the query
$item=new CacheItemClass('KEYCACHE',result,500); // implements CacheItemInterface
// configure item
CacheService::save(CacheItemInterface $item);
하지만 우리가 표의 국가나 도시를 수정하면 어떨까.아마도 이것은 조회에 영향을 주지 않을 것이다. 그러나 우리는 정말 모른다.만약 우리가 id를 안다면, 우리는 캐시를 실효시킬 수 있다
CacheService::deleteItem('KEYCACHE');
그러나 우리는 어떻게'국가 삽입'이나'도시 삽입'을 KEYCACHE와 연결합니까?우리는 PDONE(지속성)이나 라이브러리 CacheOne을 사용하여 캐시를 직접 사용할 수 있습니다
스토리지 캐시
$result=[..]; // storing the result of the query
$cache->set(['countries','cities],"KEYCACHE",result,500);
잘못된 캐시 만들기$cache->invalidate('KEYCACHE');
// or
$cache->invalidateGroup('countries'); // it invalidates all the cache stores in the group of family countries
// or
$cache->invalidateGroup('cities'); // it invalidates all the cache stores in the group of family cities
Reference
이 문제에 관하여(고급 프로그래밍: 캐시를 사용합니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/jorgecc/advanced-programming-working-with-cache-5d93텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)