search
HomeDatabaseMysql Tutorialredis 应用实践

redis 应用实践

Jun 07, 2016 pm 04:38 PM
redispracticeapplicationOpen sourceIntroductionkey value

redis 简介 redis 是一个很火的开源键值内存数据库。官方网站是 http://redis.io/。 redis的应用很广泛,就我的感觉来说,web app用的比较多。 项目中的经验 我在项目中用到了redis来作为缓存和pubsub功能,体会到了它的一些强大,这里做一下总结。 刚接触re

redis 简介

redis 是一个很火的开源键值内存数据库。官方网站是 http://redis.io/。
redis的应用很广泛,就我的感觉来说,web app用的比较多。

项目中的经验

我在项目中用到了redis来作为缓存和pubsub功能,体会到了它的一些强大,这里做一下总结。

刚接触redis时的两个命令是 get/set,很简单,set key val,就在redis的某个编号的数据库中存放了一个键值对,通过get key 可以获取这个键对应的值。和平时使用的mysql等关系型数据库有很大的区别,设置值,读取值太简洁了,这也是内存数据库的一个特点,要能够快速,简洁的添加、读取、删除值。

在我的项目中,把redis当做了一个pubsub工具来用,同时也用作了写文件的缓存。下面将分别描述一下如何使用的。

redis作为写文件的缓存

我有大概四千个文件需要被写入,源数据都是一条数据只有58字节,一秒钟大概有1000条这样的数据产生,也就是说,一秒钟要打开关闭1000个文件并写入数据,对系统和磁盘来说,都是个压力,并且这样的解决方法很有问题,很自然的就想到了用缓存。缓存了一定量的数据后,再写入文件中,减少磁盘操作,同时也提高了写入效率。

如何做缓存,如果自己来维护,就要维护4000份不同文件的缓存,用程序来维护4000份缓存,并且根据不同的缓存大小触发写文件的操作,想想都觉得困难有点大。这个时候自然地就想到了redis这个内存数据库。
redis有一个操作室 append,它向一个key追加内容,如果key不存在就创建一个,同时返回变更后的字符串长度,这个命令实在是太好用了,一下子就解决了我的问题。
通过在redis中维护4000个key,根据接收到的不同的数据,追加到不同的key上,根据返回的数据长度,当达到预期的长度后,就取出来并清空原来的值,把取出来的值写入文件中,整个过程,逻辑清晰明白。

在实际编写程序的过程中,还有一些细节需要处理,比如说,对于每一个append操作,客户端都要和redis服务器进行交互,获取提交结果,那么有无办法减少这个操作,改为批量提交呢?有的。redis有个pipeline命令,就是干这个活的,客户端通过pipeline向服务器提交数据,redis服务器不立即返回结果,而是放在一个队列中,当客户端执行了execute操作后,一次性按照提交的顺序返回执行的结果。然后再对返回的结果进行对比,寻找符合长度的数据。这样的操作,可以大幅度降低耗时,提高程序运行速度和性能。
当寻找到了符合预定长度的数据时,就使用redis的 getset(key, "") 命令,这个命令取出来key中的值,同时给key赋一个新值,这就满足了原子操作性,不会出现当一个进程对这个key取数据后,赋值新数据前,另外一个进程往这个key中写数据而导致数据的丢失的问题。找到了需要写入文件的数据后,如何通知程序写入文件呢?有同步和异步两种方法,同步就是在同一个进程/线程中继续写文件,等文件写完毕后,再做其他操作,这样的好处也许是程序实现相对简单,但是在高性能环境下,却不一定是可以接受的方法,耗时!异步呢?实现异步的方式有很多,一种是启一个新的线程去做这个时,另外一种就是用消息队列。在这个场景中,起一个新的线程去做这个事不讨好,并且也不够稳定。有一个celery的消息队列,网站自身的介绍是近乎实时的分布式消息队列。

正好,把celery拿过来用,当程序检测到符合长度后,取出来数据,通过publish的方式,通知一个sub client,subclient 接收到这个消息后,就调用celery 的task 去执行写的操作,如此,整个业务逻辑流程就串了起来,见下图的描述。

请输入图片描述

redis使用感受

redis使用起来非常的方便,同时也容易造成滥用。任何工具都有它的适用场景,有很多人拿到一个好用的工具,干什么都要用上来。我以前也犯过类似的错误,觉得c语言就是好,写一个下载网页的程序都要用c来写,结果换用python 就是几句话的事,人生苦短,不要和自己过不去,用合适的工具,完成合适的事情。

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
MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

What are common causes of poor MySQL query performance?What are common causes of poor MySQL query performance?Apr 12, 2025 am 12:11 AM

The main reasons for poor MySQL query performance include not using indexes, wrong execution plan selection by the query optimizer, unreasonable table design, excessive data volume and lock competition. 1. No index causes slow querying, and adding indexes can significantly improve performance. 2. Use the EXPLAIN command to analyze the query plan and find out the optimizer error. 3. Reconstructing the table structure and optimizing JOIN conditions can improve table design problems. 4. When the data volume is large, partitioning and table division strategies are adopted. 5. In a high concurrency environment, optimizing transactions and locking strategies can reduce lock competition.

When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.