search
HomeBackend DevelopmentPHP TutorialPHP shared cache Yac replaces APCU memcache!

This article brings you relevant knowledge about php yac. It mainly talks about how to replace APCU memcache with yac. Friends who are interested can take a look below. I hope it will be helpful to everyone.

yac cache

Yac is a shared and lock-free memory user data cache for PHP. It can be used to replace APC or local memcached. The products produced by Bird Brother must be high-quality products

Requirements

PHP 7

Install

$/path/to/phpize
$./configure --with-php-config=/path/to/php-config
$make && make install

Note

  • Yac is a lock-free cache, you should try to avoid or reduce the probability of multiple processes setting the same key

  • Yac With partial crc, you'd better rearrange the cache contents, putting the most significant (variable) bytes at the head or tail

Restrictions

  • The cache key cannot be larger than 48 (YAC_MAX_KEY_LEN) bytes

  • The cache content cannot be larger than 64M (YAC_MAX_VALUE_RAW_LEN) bytes

  • The compressed cache value cannot be larger than 1M 1M (YAC_MAX_VALUE_COMPRESSED_LEN) bytes

##ini configuration

yac.enable = 1
yac.keys_memory_size = 4M ; 4M can get 30K key slots, 32M can get 100K key slots
yac.values_memory_size = 64M
yac.compress_threshold = -1
yac.enable_cli = 0 ; 是否使用cli启用yac,默认为0
yac.serializer = php ; yac2.2.0以来,yac使用的特定seralizer json(-- enable-json) 、msgpack(-- enable-msgpack) 或igbinary(-- enable-igbinary)

Constant

YAC_VERSION
YAC_MAX_KEY_LEN = 48 ; if your key is longer than this, maybe you can use md5 result as the key
YAC_MAX_VALUE_RAW_LEN = 64M
YAC_MAX_VALUE_COMPRESSED_LEN = 1M
YAC_SERIALIZER_PHP = 0   ; since yac-2.2.0
YAC_SERIALIZER_JSON = 1  ; since yac-2.2.0
YAC_SERIALIZER_MSGPACK = 2 ; since yac-2.2.0
YAC_SERIALIZER_IGBINARY = 3 ; since yac-2.2.0
YAC_SERIALIZER  ; serializer according to yac.serializer, default is YAC_SERIALIZER_PHP

Pay attention to the problems that will occur under cli

If cli is used, the ini configuration must be enabled to enable cli-enable

<?php  
use Doraemon\pockets\datebase\ShareCache;
//实例化缓存封装类
$cache  = new ShareCache(&#39;test&#39;);
//设置缓存
$cache->set([1,2,3,5,6]);
//获取缓存
$a = $cache->get();


//备注 1.由于yac的缓存是共享的,所以在多个项目中使用时,需要注意key的唯一性,否则会出现缓存覆盖的情况
//备注 2.由于cli在执行后会自动退出,所以在cli中使用时,需要注意缓存的有效期,当再次执行时候换存是拿不到的
//例如

//例
//step 1
<?php
use Doraemon\pockets\datebase\ShareCache;
$cache  = new ShareCache(&#39;test&#39;);
//设置缓存
$cache->set([1,2,3,5,6]);
//php step1.php //执行后会自动退出,缓存失效

<?php
use Doraemon\pockets\datebase\ShareCache; 
//step 2
$cache  = new ShareCache(&#39;test&#39;);
//设置缓存
$arr = $cache->get();
var_dump($arr);// 空
//php step2.php //执行事后上一个进程已经退出,所以缓存失效

Method

Yac::__construct

Yac::__construct([string $prefix = ""])

Constructor of Yac, you can specify a prefix that will be used to prepend to any keys when performing set/get/delete

<?php
   $yac = new Yac("myproduct_");
?>

Yac::set

   Yac::set($key, $value[, $ttl = 0])
   Yac::set(array $kvs[, $ttl = 0])

Stores a value into the Yac cache, the key is unique to the cache, so storing a second value with the same key will overwrite the original value.

Return true on success, return false on error (if there is no memory, cas write right cannot be obtained)

<?php
$yac = new Yac();
$yac->set("foo", "bar");
$yac->set(
    array(
        "dummy" => "foo",
        "dummy2" => "foo",
        )
    );
?>

Note:

Such as Yac 2.1 , which may fail if cas competition fails, you may need to do the following:

while (!($yac->set("important", "value")));

Yac::get

 Yac::get(array|string $key[, &$cas = NULL])

Get the storage variable from the cache. If an array is passed, each element is obtained and returned. Returns a value on success, false on error

<?php
$yac = new Yac();
$yac->set("foo", "bar");
$yac->set(
    array(
        "dummy" => "foo",
        "dummy2" => "foo",
        )
    );
$yac->get("dummy");
$yac->get(array("dummy", "dummy2"));
?>

Yac::delete

Yac::delete(array|string $keys[, $delay=0])

Deletes the stored variable from the cache. If a delay is specified, the value will be deleted after $delay seconds.

Yac::flush

Yac::flush()

Immediately invalidate all existing items. It doesn't actually release any resources, it just marks all items as invalid.

Yac::info

Yac::info(void)

Get cache information

<?php
  ....
  var_dump($yac->info());
  /* will return an array like:
  array(11) {
      ["memory_size"]=> int(541065216)
      ["slots_memory_size"]=> int(4194304)
      ["values_memory_size"]=> int(536870912)
      ["segment_size"]=> int(4194304)
      ["segment_num"]=> int(128)
      ["miss"]=> int(0)
      ["hits"]=> int(955)
      ["fails"]=> int(0)
      ["kicks"]=> int(0)
      ["slots_size"]=> int(32768)
      ["slots_used"]=> int(955)
  }
  */
<?php
namespace Test\Cache
use Yac;
use RuntimeException;
/**
 * 共享缓存类
 * Date: 2023/2/22
 * Time: 16:13
 * docs:
 */
class ShareCache
{
    public bool $isEnable = true;
    public string $key = &#39;&#39;;
    /**
     *
     * 共享内存块实例化。
     */
    public function __construct($key)
    {
        if (!extension_loaded("yac")) {
            $this->isEnable = false;
            throw new RuntimeException(&#39;yac 扩展不存在!&#39;);
        }
        if (!$key) {
            throw new RuntimeException(&#39;key 不能为空!&#39;);
        }
        $this->key = md5($key);
    }
    /**
     *
     * 获取共享内存块的值。
     */
    public function get()
    {
        if ($this->isEnable) {
            return (new Yac(&#39;db_&#39;))->get($this->key);
        }
        throw new RuntimeException(&#39;yac is not enable ,skip getCache&#39;);
    }
    /**
     *
     * 设置共享内存块的值。
     */
    public function set($var): bool
    {
        if ($this->isEnable) {
            return (new Yac(&#39;db_&#39;))->set($this->key, $var, 3600);
        }
        throw new RuntimeException(&#39;yac is not enable ,skip setCache&#39;);
    }
    /**
     *
     * 删除共享内存块的值。
     */
    public function del(): bool
    {
        if ($this->isEnable) {
            return (new Yac(&#39;db_&#39;))->delete($this->key);
        }
        throw new RuntimeException(&#39;yac is not enable ,skip delCache&#39;);
    }
    /**
     *
     * 获取共享内存块的信息。
     */
    public function info(): array
    {
        if ($this->isEnable) {
            return (new Yac(&#39;db_&#39;))->info();
        }
        throw new RuntimeException(&#39;yac is not enable ,skip info&#39;);
    }
    /**
     *
     * 清空共享内存块的值。
     */
    public function flush(): bool
    {
        if ($this->isEnable) {
            return (new Yac)->flush();
        }
        throw new RuntimeException(&#39;yac is not enable ,skip flush&#39;);
    }
}

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of PHP shared cache Yac replaces APCU memcache!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.