Home Backend Development PHP Tutorial PHP shared cache Yac replaces APCU memcache!

PHP shared cache Yac replaces APCU memcache!

Mar 03, 2023 pm 03:47 PM
php yac

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
Copy after login

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)
Copy after login

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
Copy after login

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 //执行事后上一个进程已经退出,所以缓存失效
Copy after login

Method

Yac::__construct

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

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_");
?>
Copy after login

Yac::set

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

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",
        )
    );
?>
Copy after login

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")));
Copy after login

Yac::get

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

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"));
?>
Copy after login

Yac::delete

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

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

Yac::flush

Yac::flush()
Copy after login

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

Yac::info

Yac::info(void)
Copy after login

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)
  }
  */
Copy after login
<?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;);
    }
}
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles