How to use MemCache cache correctly in Yii framework
The specific operations are as follows:
(Recommended graphic tutorial: yii)
1. Configure the memcache server server
1. Download the memcached software package. Download address:
http://pan.baidu.com/s/1boAnghp
Unzip and put memcached.exe in any place, such as: d:/memcached/ (I unzipped it to my wampserver The bin directory is at the same level as the php directory).
2. Enter cmd using the Windows R shortcut key, enter the code in the command line, and switch to the directory of memcache.exe:
3. Enter Use the following code to install memcache.exe: memcached.exe -d install
4. Enter memcached.exe -d start to start
Configuration successful
//memcache常用的函数: Memcache::add //添加一个值,如果已经存在,则返回false Memcache::addServer // 添加一个可供使用的服务器地址 Memcache::close //关闭一个Memcache对象 Memcache::connect // 创建一个Memcache对象 memcache_debug // 控制调试功能 Memcache::decrement // 对保存的某个key中的值进行减法操作 Memcache::delete //删除一个key值 Memcache::flush // 清除所有缓存的数据 Memcache::get //获取一个key值 Memcache::getExtendedStats //获取进程池中所有进程的运行系统统计 Memcache::getServerStatus// 获取运行服务器的参数 Memcache::getStats //返回服务器的一些运行统计信息 Memcache::getVersion //返回运行的Memcache的版本信息 Memcache::increment //对保存的某个key中的值进行加法操作 Memcache::pconnect // 创建一个Memcache的持久连接对象 Memcache::replace //对一个已有的key进行覆写操作 Memcache::set //添加一个值,如果已经存在,则覆写 Memcache::setCompressThreshold //对大于某一大小的数据进行压缩 Memcache::setServerParams //在运行时修改服务器的参数
2. Install php_memcache.dll extension
1. First download the php_memcache.dll extension that matches your php version
Address:
http://pan.baidu.com/s/1skJnZIl
2. Copy and post it in your php/ext folder
3. Add the following code in php.ini and import the extension:
extension=php_memcache.dll
3. Configuration in yii
1. If you are using the basic framework: open config/web.php
If you are using the advanced framework: open config/main.php
Add the following Code:
'cache' => [ 'class' => 'yii\caching\MemCache', 'servers' => [ [ 'host' => 'localhost', 'port' => 11211, 'weight' => 100, ], [ 'host' => 'localhost', 'port' => 11211, 'weight' => 50, ], ], ],
Now you can use the following code in the action method of your controller:
//缓存MemCache $key='key'; $value='this is the value'; <pre name="code" class="php">Yii::$app->cache->set($key,$value); echo "lixian"; echo Yii::$app->cache->get($key); exit();
But when you use the expiration time:
Yii::$app->cache->set($key,$value,6);//过期时间为6s echo "lixian"; echo Yii::$app->cache->get($key); exit();
The output cannot be done. This is a bug in the framework itself. The solution is as follows:
Configure the corresponding parameters according to the document before using memcache in yii2. You will find this when using memcache (non-memcached). Yii::$app->cache->set('key','value'); When this sentence does not set the validity time in seconds, the value of the key in the cache can be obtained normally, but it means that the key will not expire.
When the valid time is set, Yii::$app->cache->set('key','value',60); For example, after 60 seconds, it will appear that the value corresponding to the key cannot be obtained. I have searched online and in forums, but I have not found a solution. Many PHPers have encountered similar problems. So I went to take a look at the underlying code. The referenced memcache class is yii\caching\MemCache that comes with Yii2. Yii::$app->cache->set('key','value') This code will automatically call the setValue method under the memcache class to set the cache, so the problem may arise here.
After testing later, I found the last sentence of this method return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire ) problem, change this code to return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $duration ) Afterwards, I tested again and found that the problem had been solved.
The reason is that it is called when memcache is used in this return code. $this->_cache->set($key, $value, 0, $expire) , equivalent to $mem = new Memcache();$mem->set($key,$value,0,$expire); The most critical point here is: the time to be set by memcache means how many seconds the effective time is, and the time to be set by memcached means the second at which it will expire (equivalent to time() $duration), so the problem is found Afterwards, the problem was solved by changing the second $expire in the original code to $duration.
The above is the detailed content of How to use MemCache cache correctly in Yii framework. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

Writing clear and comprehensive documentation is crucial for the Golang framework. Best practices include following an established documentation style, such as Google's Go Coding Style Guide. Use a clear organizational structure, including headings, subheadings, and lists, and provide navigation. Provides comprehensive and accurate information, including getting started guides, API references, and concepts. Use code examples to illustrate concepts and usage. Keep documentation updated, track changes and document new features. Provide support and community resources such as GitHub issues and forums. Create practical examples, such as API documentation.

Choose the best Go framework based on application scenarios: consider application type, language features, performance requirements, and ecosystem. Common Go frameworks: Gin (Web application), Echo (Web service), Fiber (high throughput), gorm (ORM), fasthttp (speed). Practical case: building REST API (Fiber) and interacting with the database (gorm). Choose a framework: choose fasthttp for key performance, Gin/Echo for flexible web applications, and gorm for database interaction.

In Golang applications, caching and locking are closely related. Caches are used to speed up data access, while locks are used to control concurrent access to shared resources. Cached data can be read by multiple processes at the same time, and modifying data in the cache requires the use of locks to ensure data integrity. Modifications to the persistent cache also require the use of locks to prevent other processes from modifying the data at the same time. In practical cases, read-write locks can be used to protect the cache to ensure that multiple processes do not write to the cache at the same time before modifying the cache. Understanding the relationship between caching and locking is critical to building Golang applications with excellent concurrency and performance.

In Go framework development, common challenges and their solutions are: Error handling: Use the errors package for management, and use middleware to centrally handle errors. Authentication and authorization: Integrate third-party libraries and create custom middleware to check credentials. Concurrency processing: Use goroutines, mutexes, and channels to control resource access. Unit testing: Use gotest packages, mocks, and stubs for isolation, and code coverage tools to ensure sufficiency. Deployment and monitoring: Use Docker containers to package deployments, set up data backups, and track performance and errors with logging and monitoring tools.

There are five misunderstandings in Go framework learning: over-reliance on the framework and limited flexibility. If you don’t follow the framework conventions, the code will be difficult to maintain. Using outdated libraries can cause security and compatibility issues. Excessive use of packages obfuscates code structure. Ignoring error handling leads to unexpected behavior and crashes.
