search
HomeBackend DevelopmentPHP Tutorialmemcache与redis替代session如何?是不是有redis就不需要memcache了?

看了知乎与segmentfault的架构,都是用的是redis,但是这个session存储也用的是redis吗?

回复内容:

看了知乎与segmentfault的架构,都是用的是redis,但是这个session存储也用的是redis吗?

Memcached创建者Dormando很早就写过两篇文章[1][2],告诫开发人员不要用memcached存储Session.

http://mp.weixin.qq.com/s?__biz=MjM5NjQ4MjYwMQ==&mid=202805903&idx=2&sn=94d0c60d0f86672aac527b658b7e1bcd#rd

1)首先redis和memcache(后面简写mc)取舍问题。
在很多mc的应用场景下,都可以使用redis也是可行的解决方案。当key比较大的时候,mc有更好的性能。当让mc存在key的大小限制(默认参数最大允许存1MB的字符串,-I参数的默认值)。
而redis在key较大的情况,读写性能非常低效。而选择mc有更好的性能和吞吐量
下面是生产上的测试,200并发的情况系,单个key为500kB的情况下。

<code>     redis-benchmark -d 500000 -t get,set -n 1000 -c  200 -q 
     SET: 306.84 requests per second
     GET: 1449.28 requests per second
</code>

redis的优势主要体现在两方面:
1)丰富的数组结构,无疑提高了开发效率。list(queue)、set/zset、hashmap、HyperLogLog非常好用。
redis is a data structure server。构建简单的消息队列,set去重操作,hashmap存放简单的关系型数据,HyperLogLog做唯一计数,等等。
2)redis支持主从复制,对与构建支持auto-failover的ha方案提供了必要的条件--multi replicas。比如简单的keepalive + vip的方式。
3)另外,twemproxy,redis sentinel、redis-cluster的出现,可以让运维或者DBA构建大规模的分布式缓存系统。(我本人是DBA)
具体的对比,查看[http://segmentfault.net/q/1010000002588088?_ea=147671][1]。

2)关于session存储。
session是web服务器端存放的用户行为数据,存储方式有很多中。比如nfs共享文件系统,tomcat集群提供了共享session存储。其他的用db(RDBMS)存储的也有。
nosql出现之后,常见的选择有redis、mc、mongodb。redis、mc的php直接提供调用模块(函数),都很方便使用。
虽然很多人说,session存储crash了,影响不大,大不了用户重新登录。但是我觉得session数据千万不能丢失。
1)首先,session数据丢失,用户需要重新登录,用户的体验非常差。
2)对一些购物网站,session的数据更为重要。session数据对于追踪用户的行为非常重要,比如做推荐系统、网站防刷系统(是否是机器人在爬去数据)。
因而我个人比较认同mc开发的观点,不要使用mc作为session存储。而选择redis,可以做数据复制和ha方案的。

楼主应该说的是替代默认的file的session。
一般来说用memcache就好了,
除非项目其他地方用了redis,那就也存redis吧,

有了redis就不需要memcache,有了memcache就不需要redis。
不是一定不能,而是没必要搞那么复杂。

1.SESSION是一种储存机制,而不是软件
2.虽然redis和memcache有很多地方都一样。但是储存临时性数据,还是memcache比较合适。redis主要是数据在内存中,定时或者定量写入,因此读取和写入都很快
3.SESSION既可以储存在memcache中,也可以储存在redis中。但是考虑到SESSION的临时性,个人认为更适合储存在memcache中

使用Redis实现Session共享,最重要的一个原因在于,Redis支持Hash结构(Session本质上就是服务器维护的一个哈希表)。

假设一个场景来说明,现在要在Session中要存入用户ID、用户头像两个字段信息,如果使用Memcached存储,有两种方式来存储:

  1. 将用户ID、用户头像分别使用两个Key来存储,key1 = #userId、key2 = #avatar

  2. 使用一个Map结构将用户ID、用户头像两个字段包装起来,如此可以将用户ID及头像信息视作一个对象来存储,key = {userId : #userId ,avatar : #avatar}

现有一个业务,需要从Session中取出#userId信息,第一种存储方式,可以直接使用key1找到#userId,第二种则需要使用key将包装过的用户信息整体取出,再取出其中的#userId信息,由此不难看出,第二种方式比较浪费网络资源。第一种方式看似可用,其实也是一个坑~
现有另一个业务,需要从Session中同时取出#userId和#avatar两个字段信息,第一种方式则需要分别使用key1和key2进行两次网络交互才能取得所需信息(字段数量越多,网络开销也越大),反而使用第二种式,更加合算。由此可见使用memcached来实现Session共享是不合适的。
同样的业务场景,使用Redis,可以将用户信息以Hash结构存储,同样将用户信息作为一个整体存入:

# 将用户信息作为一个整体写入Redis
HMSET key userId #userId avatar #avatar name #name
# 一次取出全部字段信息
HGETALL key
# 只取出其中一个或多个字段
HGET key name
HMGET key name avatar
...

由示例可以看出无论是取出部分信息还是全部信息,网络开销都只需要一次,写入也是同样的道理,仅此一点,也能证明Redis比Memcached更适合用来实现Session共享。

Statement
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
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools