Redis Database Installation configuration uses

Source: Internet
Author: User

Tags: PHP cache Storage System Performance testing requirements


Redis is an open source API that is written in ANSI C, supports the web, can be persisted in memory, key-value databases, and provides multiple languages. Redis is a key-value storage system. Similar to memcached, it supports storing more value types, including string (string), list (linked list), set (set), Zset (sorted set-ordered collection), and hash (hash type). These data types support Push/pop, Add/remove, and intersection-set and difference sets, and richer operations, and these operations are atomic. Based on this, Redis supports sorting in a variety of different ways. As with memcached, data is cached in memory to ensure efficiency. The difference is that Redis periodically writes the updated data to disk or writes the modified operation to the appended record file, and Master-slave (Master-Slave) synchronization is implemented on this basis. Chinese Official document: http://www.redis.cn/documentation.html

Installing Redis
Official website: http://redis.io/
Official download: Http://redis.io/download can download different versions as needed
Windows Edition: Https://github.com/mythz/redis-windows

Installing Redis,redis code follows ANSI-C and can be run on all POSIX systems (such as Linux, *bsd, Mac OS X, Solaris, etc.). And Redis does not rely on any nonstandard libraries, and no compilation parameters are required to be added. The installation of Redis is surprisingly simple.
Download Source: wget http://redis.googlecode.com/files/redis-2.4.6.tar.gz
Unzip the installation:
$ wget http://download.redis.io/releases/redis-2.8.19.tar.gz
$ tar xzf redis-2.8.19.tar.gz
$ CD redis-2.8.19
$ make
$ make Install
If make continues to error, the information is as follows: Error:jemalloc/jemalloc.h:no such file or directory
Execute make MALLOC=LIBC on the line
Note that, in order to prevent an accident, make a clean-up after doing a failure

Redis consists of four executable files in the SRC folder of the source bundle: Redis-benchmark, REDIS-CLI, Redis-server, Redis-stat, four files, Adding a redis.conf constitutes the final available package for the entire redis. Their role is as follows:
Redis-server:redis Server Daemon Startup program
Redis-cli:redis command-line operation tool. Of course, you can also use Telnet to operate on its plain text protocol.
Redis-benchmark:redis Performance testing tools to test the read and write performance of Redis in your system and in your configuration
Redis-stat:redis Status Detection Tool to detect Redis current status parameters and delay status
(Redis-benchmark redis-check-aof redis-check-dump redis-cli redis-sentinel redis-server)
Copy the command to the/usr/local/bin directory and copy the configuration file redis.conf to the/etc/directory
Now it's ready to start, and Redis has only one boot parameter, which is his profile path.

The start command is as follows: redis-server/etc/redis.conf

Note that the Daemonize parameter for the default copy of the past redis.conf file is no, so Redis does not run in the background, so we need to reopen a terminal to test it. Modify to Yes to run Redis in the background. In addition, the configuration file specifies the address of the PID file, log file and data file, if necessary, the default log information is directed to stdout.
Add to
Vm.overcommit_memory=1
Refresh the configuration to make it effective
Sysctl Vm.overcommit_memory=1
Additional Information:
* * If the memory situation is very tense, you need to set the kernel parameters:
Echo 1 >/proc/sys/vm/overcommit_memory

The kernel parameters are described below:
The Overcommit_memory file specifies the kernel's policy for memory allocation, which can be 0, 1, 2.
0, indicates that the kernel will check for sufficient available memory to be used by the process, and if sufficient memory is available, the memory request is allowed; otherwise, the memory request fails and the error is returned to the application process.
1, which means that the kernel allows all physical memory to be allocated regardless of the current memory state.
2, which indicates that the kernel allows allocating more memory than the sum of all physical memory and swap space
Edit the redis.conf configuration file (/etc/redis.conf) to make the appropriate adjustments as required, such as:
Daemonize Yes #转为守护进程, otherwise output a row of monitoring information every 5 seconds at startup
Save #减小改变次数, in fact, this can be specified according to the situation
MaxMemory 256000000 #分配256M内存

The following are the meanings of the main configuration parameters of redis.conf:
Daemonize: Whether to run later Daemon (daemon) mode
Pidfile:pid File Location
Port: Port number for listening
Timeout: Request time-out
Loglevel:log Information level
Logfile:log File Location
Databases: number of open databases
Save *: How often the snapshot is saved, the first * indicates how long, and the third * indicates how many times the write operation is performed. Snapshots are automatically saved when a certain number of writes are performed within a certain amount of time. You can set multiple conditions.
Rdbcompression: Whether to use compression
Dbfilename: Data Snapshot file name (only file name, excluding directory)
Dir: Save directory for Data snapshot (this is the directory)
AppendOnly: If the appendonlylog is turned on, each write will record a log, which will improve the data anti-risk ability, but affect the efficiency.
Appendfsync:appendonlylog How to sync to disk (three options, each write is forced to call Fsync, Fsync per second, do not call Fsync wait for the system to synchronize itself)

At this point you can open a terminal for testing, the default listening port in the configuration file is 6379, do not start the test first, the command format is as follows:
Redis-cli.exe-h 192.168.10.61-p 6379

[[Email protected] ~] #redis-cli
Could not connect to Redis at 127.0.0.1:6379:connection refused
Not connected> exit
[Email protected] ~]# redis-server/etc/redis.conf
[Email protected] ~]# REDIS-CLI
Redis 127.0.0.1:6379> quit

REDIS Data Structures
The Redis author, Antirez, once called it a data structure server (data Structures server), which is a very accurate statement that all of Redis's functions are to store data in several of its inherent structures and provide interfaces to the user to manipulate these structures. We can imagine those intrinsic data types and their operations in various languages.

Redis currently offers four types of data: String,list,set and Zset (sorted set) and hash.
String is the simplest type, you can understand it as a type with memcached, a key corresponds to a value, and the operation supported on it is similar to the operation of Memcached. But it's more versatile.
List is a linked list structure, the main function is push, pop, get all the values of a range and so on. Key in operation is understood as the name of the linked list.
Set is a set, and we are similar to the concept of the set in mathematics, the operation of the set has added delete elements, there are multiple sets of orthogonal and poor operation. In Operation Key is understood as the name of the collection.
Zset is an upgraded version of set, and he adds a sequential attribute on the set, which can be specified when adding a modified element, and Zset automatically re-adjusts the order of the new values after each assignment. It can be understood that there are two columns of MySQL table, one column of value, and one in the order of storage. Key in operation is understood as the name of Zset.
The hash data type allows users to use Redis to store object types, and one important advantage of the hash data type is that when you store data objects with very few key values, the memory consumption of the data store is small. For more information on hash data types, see:/http Code.google.com/p/redis/wiki/hashes

Each data type provides the appropriate action method, to use these methods, the first to install the redis PHP extension \php_redis-5.5-vc11-ts-x86 My version of PHP5.5 to correspond, in the PHP configuration file to add
Extension=php_igbinary.dll
Extension=php_redis.dll


Restart Apache,phpinfo () to see the results as follows.


Write PHP code to connect to Redis server, complete the simple operation:
<?php
$redis = new Redis (); #实例化redis类
$redis->connect (' 192.168.1.251 '); #连接服务器
$redis->set (' key ', ' hello '); #调用方法, sets the string type value
$redis->append (' key ', ' world '); #修改string类型值
echo $redis->get (' key '); #获取redis the value of key and outputs the display
echo $redis->type (' key '); Types of Data #获取key
echo $redis->echo (' would close ... '); # output string
$redis->close (); #关闭连接

Some of the properties and methods of the Redis class are listed below
A) Connect to Redis server:
Connect: Connecting to server
Pconnect: Long Connection
AUTH: Permission Validation
Select: Choose DB
Close: Closing the connection
SetOption: Set client options
GetOption: Get Client options
ping:ping Redis Server
Echo: Output string

Note that if you operate redis frequently, and the connect and close will be very expensive, it is recommended to use Pconnect to establish a long connection.
b) string read and write function
Append: Append a value after a value
DECR: decrements the value of a key
INCR: Increments the value of a key
Get: Get a value
Set: Sets a value
Getset: Sets the value and returns the old value
MGet: Bulk Fetch values
MSet: Batch Setting values
Strlen: Get value length
Note: If you can use bulk operations as much as possible, reduce the frequent connection to Redis database performance
c) hash read and write function
Hdel: Delete a multiple domain
Hexists: Determine if a hash field exists
Hget: Gets the value of the hash field
Hgetall: Get all domain values
Hincrby: Self-growing value of a hash int field
Hkeys: Get hash all fields
Hlen: Get the number of domains
Hmget: Bulk Get the value of a domain
Hmset: Bulk set values for a field
Hset: Setting the value of a field
Hvals: Get values for all domains
d) List read and write function
Linsert: inserting elements
Llen:list length
Lpop: Remove and get the first color
Lpush: Inserting an element
Lrem: removing elements
LSet: Setting element values
E) Set
Sadd: Add one or more members
Sismember: Whether it contains
Smembers: Get member
Smove: Moving Members
SPop: removing members
Srandmember: Get random Members
Srem: Delete
f) Sorted set
Zadd: Add one or more
Zcard: Number of Members
Zincrby: Incrementing member score
Zrange: Returns a member within an index range
Zrangebyscore: Returns members within the score range
Zscore: Get member Score
Zrem: Remove one or more members

For more information, please refer to: Https://github.com/nicolasff/phpredis

redis.conf Configuration parameters:
1) daemonize On|yes
Redis is not run as a daemon by default, and can be modified by this configuration item, enabling the daemon when you use Yes
2) Pidfile/var/run/redis_6379.pid
When Redis is running as a daemon, the system defaults to writing the PID to/var/run/redis.pid, and the PID file can be specified by pidfile
3) Port 6379
Redis Default Listener 6379 port, you can specify the port to listen for Redis via port
4) Bind 127.0.0.1
Bind host Address
5) Unixsocket/tmp/redis.sock
Specify the UNIX socket path for Redis listening
6) Timeout 300
When the client is idle for a period of time, close the connection, unit seconds
7) LogLevel verbose|debug|notice|warning
Specify logging level, default is verbose
8) Logfile/var/log/redis_6379.log
Logging file, default is standard output stdout, if Redis runs as daemon, logfile is configured as stdout, logs will output to/dev/null
9) syslog-enabled No|yes
When configured to Yes, the log is output to the system log and the default is no

) Syslog-ident Redis
Specify the identifier for the syslog
One) syslog-facility local0
Specify the Syslog device (facility), either user or local0 to LOCAL7
) Databases 16
Set the number of databases in Redis, the default database is DB 0, and you can select the database to use with select <dbid&gt. Dbis is greater than or equal to 0, less than or equal to Databases-1 "here is 16-1"
Save <seconds> <changes>
Specify how long, how many update operations to synchronize data to the database file, you can mate with multiple conditions, the system default configuration is as follows:
Save 1 #900秒 1 changes
Save #300秒 10 Updates
Save 10000<span style= "White-space:pre" > </span> #60秒 10,000 updates
Note that if you do not persist "do not write data to disk", comment out save.
) Rdbcompression Yes|no
When the data dumps to the data file, the system compresses the string object data, and the system defaults to Yes. If you want to save the CPU, you can set it to no, when the data file is larger than the LZF compression
) Dbfilename Dump.rdb
Specify the database file name, default is Dump.rdb
dir/var/lib/redis/6379)
Specify local Database storage directory
Slaveof <masterip> <masterport>
When this machine is a slave service, set the IP and port of the master service
) Masterauth <master-password>
When the Master service has a password set, the slave service connects to the master password. If the configuration is not correct, the slave service request will be rejected
) Slave-serve-stale-data Yes|no
When the connection between slave and master is disconnected or slave is synchronizing with master, if there is a slave request, slave can request the client when the Slave-serve-stale-data is configured to Yes, and when no, Slave will respond to error, default is yes
) Requirepass foobared
Set up a Redis connection password
) MaxClients 128
Set the maximum number of client connections at the same time, which is unlimited by default. If you set maxclients 0 o'clock, it means that you do not limit
MaxMemory <bytes>
Specifies the Redis maximum memory limit, which, when Redis starts, loads data into memory, and when it reaches the maximum memory, Redis clears the expired or expired key, still reaches the maximum memory setting, and will no longer be able to write, but still be able to read the operation
Maxmemory-policy)
Volatile-lru|allkeys-lru|volatile-random|allkeys->random|volatile-ttl|noeviction
What policy to use to remove in-memory data when Redis uses memory to reach maximum
) AppendOnly No|yes
Specifies whether to log after each update operation, the default configuration is no, that is, asynchronously writes data to disk and, if not turned on, may cause partial data loss in the event of a power outage
) Appendfilename appendonly.aof
Specifies the update log file name "AoF log", which defaults to appendonly.aof
) Appendfsync Everysec|no|aways
Specify the update log condition, no indicates that the AoF file (fast) that the operating system synchronizes the data cache to the disk (quick) always represents a aof file (slow, secure) that manually calls Fsync to write data to disk after each update operation
Everysec, indicating synchronization once per second (split, default)
) Slowlog-log-slower-than 10000
Configure the conditions for logging slow logs, the unit is subtle, when a negative value is turned off slow logging, when it is 0 o'clock, all operations are logged
) Slowlog-max-len 1024
Configure the maximum number of records for slow queries
) Hash-max-zipmap-entries 512
Configure the maximum number of elements, Redis uses a special hash algorithm when the configuration data is exceeded
) Hash-max-zipmap-value 64
Configure the maximum element value, using a special hash algorithm when Tsaoko configuration values
) Activerehashing Yes
Specifies whether to activate the reload hash, which is turned on by default

You can use the following command to start the Redis service using the configuration file redis.conf
/usr/local/redis/bin/redis-server/usr/local/redis/etc/redis.conf

Redis Database Installation configuration uses

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: