Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Redis

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article is about how to use Redis. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

A brief introduction to Redis

What is Redis? Full name: REmote DIctionary Server is a log-type, Key-Value high-performance database that supports network, memory-based and persistence, and provides API in multiple languages. It is often referred to as a data structure server, because the value can be String, Map, list, sets, sorted sets, and so on:

String: string

Hash: hash

List: list

Set: collection

Sorted Set: ordered set

It is a non-relational database relative to a relational database.

Second, advantages

Redis and other key-value cache products have the following three features:

Redis supports data persistence. You can save the data in memory on disk and load it again when you restart it.

Redis not only supports simple key-value type data, but also provides storage of data structures such as list,set,zset,hash.

Redis supports data backup, that is, data backup in master-slave mode.

III. Redis installation

The installation of Redis is easy. Download it from https://github.com/MSOpenTech/redis/releases. Then download "Redis-x64-xx.x.xxx.zip" and put it in your favorite location to extract it, double-click "redis-server.exe" to start the Redis service according to the default configuration; double-click "redis-cli.exe" to open the client console to command and operate the Redis service.

You can also:

Open a cmd window and use the cd command to change directories to C:\ redis to run redis-server.exe redis.windows.conf.

Execute redis-cli.exe-h 127.0.0.1-p 6379 to enter client mode

"- h" specifies the Redis server host

"- p" specifies the Redis server port

IV. Redis configuration

The configuration file for Redis is located in the Redis installation directory and the file name is redis.conf.

You can view or set configuration items through the * * "CONFIG" * * command.

CONFIG GET 'CONFIG_SETTING_NAME' / / get the corresponding parameter configuration CONFIG GET * / / get all parameter configuration CONFIG SET "CONFIG_SETTING_NAME"NEW_CONFIG_VALUE" / / set the corresponding parameter values

Parameter description

The redis.conf configuration items are described as follows:

1.Redis does not run as a daemon by default. It can be modified by this configuration item to enable the daemon using yes.

Daemonize no

two。 When Redis runs as a daemon, Redis writes pid to the / var/run/redis.pid file by default, which can be specified through pidfile

Pidfile / var/run/redis.pid

3. Specify the Redis listening port, and the default port is 6379. In a blog post, the author explains why 6379 is chosen as the default port, because 6379 has the number corresponding to MERZ on the phone button, and MERZ is named after Italian singer Alessia Merz.

Port 6379

4. Bound host address

Bind 127.0.0.1

5. When the client has been idle for how long, the connection is closed. If specified as 0, the function is disabled.

Timeout 300

6. Specifies the logging level. Redis supports a total of four levels: debug, verbose, notice, and warning. The default is verbose.

Loglevel verbose

7. Logging method. Default is standard output. If Redis is configured to run in daemon mode, and here the logging mode is configured as standard output, the log will be sent to / dev/null.

Logfile stdout

8. Set the number of databases. The default database is 0. You can use the SELECT command to specify the database id on the connection.

Databases 16

9. Specify how long and how many update operations will synchronize the data to the data file, which can be matched by multiple conditions.

Save

Three conditions are provided in the Redis default configuration file:

Save 900 1 save 300 10 save 60 10000

It represents 1 change in 900 seconds (15 minutes), 10 changes in 300 seconds (5 minutes), and 10000 changes in 60 seconds.

10. Specify whether to compress data when stored in the local database. The default is that yes,Redis uses LZF compression. If you want to save CPU time, you can turn this option off, but it will cause the database file to become huge.

Rdbcompression yes

11. Specifies the local database file name, which defaults to dump.rdb

Dbfilename dump.rdb

twelve。 Specify the local database storage directory

Dir. /

13. Set the IP address and port of the master service when the machine is a slav service. When Redis starts, it automatically synchronizes data from master.

Slaveof

14. When the master service is password protected, the password of the slav service connection master

Masterauth

15. Set the Redis connection password. If the connection password is configured, the client needs to provide the password through the AUTH command when connecting to the Redis. It is disabled by default.

Requirepass foobared

16. Set the maximum number of client connections at a time. By default, there is no limit. The number of client connections that Redis can open at the same time is the maximum number of file descriptors that can be opened by Redis processes. If you set maxclients 0, there is no limit. When the number of client connections reaches the limit, Redis closes the new connection and returns a max number of clients reached error message to the client

Maxclients 128

17. Specify the maximum memory limit of Redis. Redis will load data into memory at startup. After reaching the maximum memory, Redis will first try to clear the expired or expiring Key. When this method is processed, the maximum memory setting will still be reached, and the write operation will no longer be performed, but the read operation can still be performed. Redis's new vm mechanism stores Key in memory and Value in swap area.

Maxmemory

18. Specifies whether to log after each update operation. Redis writes data to disk asynchronously by default. If it is not enabled, it may result in data loss for a period of time in the event of a power outage. Because redis itself synchronizes data files according to the above save conditions, some data will only exist in memory for a period of time. Default is no

Appendonly no

19. Specify the update log file name. Default is appendonly.aof.

Appendfilename appendonly.aof

20. Specify the update log condition. There are 3 optional values:

No: indicates that the operating system synchronizes the data cache to disk (fast)

Always: means to manually call fsync () after each update operation to write data to disk (slow, secure)

Everysec: indicates synchronization once per second (eclectic, default)

Appendfsync everysec

21. Specify whether to enable the virtual memory mechanism. The default value is no. For a brief introduction, the VM mechanism stores the data in pages. Redis will swap the cold data on the disk, which is less visited, and the pages that visit more will be automatically swapped out to memory by the disk (I will carefully analyze the VM mechanism of Redis in a later article).

Vm-enabled no

twenty-two。 Virtual memory file path. Default is / tmp/redis.swap, which cannot be shared by multiple Redis instances.

Vm-swap-file / tmp/redis.swap

23. All data larger than vm-max-memory is stored in virtual memory, no matter how small the vm-max-memory setting is, all index data is stored in memory (Redis's index data is keys), that is, when vm-max-memory is set to 0, all value actually exists on disk. Default value is 0

Vm-max-memory 0

24.Redis swap files are divided into many page. An object can be stored on multiple page, but a page cannot be shared by multiple objects. Vm-page-size should be set according to the size of the stored data. The author suggests that if many small objects are stored, the page size should be set to 32 or 64bytes. If large objects are stored, a larger page can be used. If you are not sure, use the default value.

Vm-page-size 32

25. Set the number of page in the swap file, because the page table (a type of bitmap that indicates that the page is idle or used) is placed in memory, every 8 pages on disk will consume 1byte's memory.

Vm-pages 134217728

twenty-six。 Set the number of threads to access the swap file, it is best not to exceed the number of cores of the machine, if set to 0, then all operations on the swap file are serial, which may cause a long delay. The default value is 4

Vm-max-threads 4

twenty-seven。 Sets whether to merge smaller packets into a single packet when replying to the client. Default is on.

Glueoutputbuf yes

twenty-eight。 Specifies that a special hash algorithm is used when the number of elements exceeds a certain number or the largest element exceeds a critical value.

Hash-max-zipmap-entries 64hash-max-zipmap-value 512

twenty-nine。 Specifies whether to activate reset hashing, which is enabled by default (more on later when introducing Redis's hashing algorithm)

Activerehashing yes

thirty。 Specify to include other profiles that can use the same profile between multiple Redis instances on the same host, while each instance has its own specific profile

Include / path/to/local.conf

5. Redis data type

String: string

Hash: hash

List: list

Set: collection

Sorted Set: ordered set

1.String (string)

String is the most basic type of redis, which you can understand as exactly the same type as Memcached, with a key corresponding to a value.

The string type is binary safe. It means that the string of redis can contain any data. Such as jpg images or serialized objects.

String type is the most basic data type of Redis, and a key can store 512MB as much as possible.

Redis 127.0.0.1 OKredis 6379 > SET name "xlosy" OKredis 127.0.0.1 xlosy > GET name "xlosy"

In the above example, we used Redis's SET and GET commands. The key is name and the corresponding value is xlosy.

2.Hash (hash)

Redis hash is a collection of key-value pairs (key= > value).

Redis hash is a mapping table for field and value of type string, and hash is particularly suitable for storing objects.

Redis > HMSET myhash field1 "Hello" field2 "World"OK" redis > HGET myhash field1 "Hello" redis > HGET myhash field2 "World"

In the example, we use the Redis HMSET and HGET commands. HMSET sets two field= > value pairs, and HGET gets the corresponding value of the corresponding field.

3.List (list)

The Redis list is a simple list of strings sorted in the order in which they are inserted. You can add an element to the head (left) or tail (right) of the list.

Redis 127.0.0.1 redis 6379 > lpush xlosy redis (integer) 1redis 127.0.0.1 1redis 6379 > lpush xlosy mongodb (integer) 2redis 127.0.0.1 integer 6379 > lpush xlosy rabitmq (integer) 3redis 127.0.0.1 lrange xlosy 0101) "rabitmq" 2) "mongodb" 3) "redis"

Lists can store up to 232-1 elements (4294967295, each list can store more than 4 billion).

4.Set (collection)

The Set of Redis is an unordered collection of type string.

The collection is implemented through a hash table, so the complexity of adding, deleting, and finding is all O (1).

Redis 127.0.0.1 redis 6379 > sadd xlosy redis (integer) 1redis 127.0.0.1 1redis 6379 > sadd xlosy mongodb (integer) 1redis 127.0.0.1 1redis 6379 > sadd xlosy rabitmq (integer) 1redis 127.0.0.1 integer 6379 > sadd xlosy rabitmq (integer) 0redis 127.0.0.1 1redis 6379 > smembers xlosy 1) "redis" 2) "rabitmq" 3) "mongodb"

Note: rabitmq has been added twice in the above example, but depending on the uniqueness of the elements in the collection, the second inserted element will be ignored.

The maximum number of members in the collection is 4294967295 (each collection can store more than 4 billion members).

5.zset (sorted set: ordered set)

Redis zset, like set, is a collection of elements of type string, and duplicate members are not allowed.

The difference is that each element is associated with a score of type double. Redis sorts the members of the collection from small to large by scores.

The members of the zset are unique, but the score can be repeated.

Redis 127.0.0.1 1redis 6379 > zadd xlosy 0redis (integer) 1redis 127.0.0.1 integer 6379 > zadd xlosy 0 mongodb (integer) 1redis 127.0.0.1 1redis 127.0.0.1 integer > zadd xlosy 0 rabitmq (integer) 0redis 127.0.1 Frey 6379 > ZRANGEBYSCORE xlosy 0 10001) "mongodb" 2) "rabitmq" 3) "redis"

VI. Redis command

Ping: command to verify that the service is started

$redis-cli-h 127.0.0.1-p 6379-a "mypass" / / "- h" is the host address, "- p" is the host port, and "- a" is the host password redis 127.0.0.1

If you output pong after executing the ping command, the Redis server is running normally.

* * 1) .Redis command for key operation * *

SET: adding key valu

Redis 127.0.0.1 6379 > SET xlosykey redisOK

DEL: delete existing key values

Redis 127.0.0.1 redis 6379 > DEL xlosykey (integer) 1

1 DEL key

This command is used to delete the key when the key exists.

2 DUMP key

Serializes the given key and returns the serialized value.

3 EXISTS key

Check whether the given key exists.

4 EXPIRE key seconds

Sets the expiration time for the given key.

5 EXPIREAT key timestamp

EXPIREAT is similar to EXPIRE in that it is used to set the expiration time for key. The difference is that the time parameter accepted by the EXPIREAT command is the UNIX timestamp (unix timestamp).

6 PEXPIRE key milliseconds

Sets the expiration time of key in milliseconds.

7 PEXPIREAT key milliseconds-timestamp

Sets the timestamp (unix timestamp) of key expiration time in milliseconds

8 KEYS pattern

Find all key that match the given pattern (pattern).

9 MOVE key db

Move the key of the current database to the given database db.

10 PERSIST key

Remove the expiration time of key, and key will persist.

11 PTTL key

Returns the remaining expiration time of the key in milliseconds.

12 TTL key

Returns the remaining time to live (TTL, time to live) for a given key in seconds.

13 RANDOMKEY

A key is randomly returned from the current database.

14 RENAME key newkey

Modify the name of key

15 RENAMENX key newkey

Rename key to newkey only if newkey does not exist.

16 TYPE key

Returns the type of value stored by key.

For more commands, please refer to https://redis.io/commands

2) commands for string (String) manipulation by .Redis

Redis 127.0.0.1 SET xlosykey redisOKredis 6379 > GET xlosykey "redis"

1 SET key value

Sets the value of the specified key

2 GET key

Gets the value of the specified key.

3 GETRANGE key start end

Returns the subcharacters of the string value in key

4 GETSET key value

Sets the value of the given key to value and returns the old value of key (old value).

5 GETBIT key offset

Gets the bit (bit) at the specified offset for the string value stored by key.

6 MGET key1 [key2...]

Gets all (one or more) values of a given key.

7 SETBIT key offset value

Sets or clears the bit (bit) on the specified offset for the string value stored by key.

8 SETEX key seconds value

Associate the value value to key and set the expiration time of key to seconds (in seconds).

9 SETNX key value

The value of key is set only if key does not exist.

10 SETRANGE key offset value

Overwrites the string value stored in a given key with the value parameter, starting with the offset offset.

11 STRLEN key

Returns the length of the string value stored by key.

12 MSET key value [key value...]

Set one or more key-value pairs simultaneously.

13 MSETNX key value [key value...]

Set one or more key-value pairs at the same time if and only if none of the given key exists.

14 PSETEX key milliseconds value

This command is similar to the SETEX command, but it sets the lifetime of the key in milliseconds, rather than seconds, as the SETEX command does.

15 INCR key

Increments the numerical value stored in key by one.

16 INCRBY key increment

Adds the value stored by key to the given incremental value (increment).

17 INCRBYFLOAT key increment

Adds the value stored by key to the given floating-point increment value (increment).

18 DECR key

Subtracts the numeric value stored in key by one.

19 DECRBY key decrement

The value stored by the key minus the given decrement.

20 APPEND key value

If the key already exists and is a string, the APPEND command appends the specified value to the end of the original value of the key (value).

For more commands, please refer to https://redis.io/commands

3) .Redis commands for hash (Hash) operations

127.0.1 HMSET xlosykey name "redis tutorial" description "redis basic commands for caching" likes 20 visitors 23000OK127.0.0.1:6379 > HGETALL xlosykey 1) "name" 2) "redis tutorial" 3) "description" 4) "redis basic commands for caching" 5) "likes" 6) "20" 7) "visitors" 8) "23000"

1 HDEL key field1 [field2]

Delete one or more hash table fields

2 HEXISTS key field

Check whether the specified field exists in the hash table key.

3 HGET key field

Gets the value of the specified field stored in the hash table.

4 HGETALL key

Gets all the fields and values that specify key in the hash table

5 HINCRBY key field increment

Adds an incremental increment to the integer value of the specified field in the hash table key.

6 HINCRBYFLOAT key field increment

Adds an incremental increment to the floating-point value of the specified field in the hash table key.

7 HKEYS key

Get all the fields in the hash table

8 HLEN key

Gets the number of fields in the hash table

9 HMGET key field1 [field2]

Get the values of all given fields

10 HMSET key field1 value1 [field2 value2]

Multiple field-value (field-value) pairs are set to the hash table key at the same time.

11 HSET key field value

Set the value of field field in the hash table key to value.

12 HSETNX key field value

Set the value of the hash table field only if the field field does not exist.

13 HVALS key

Get all values in the hash table

14 HSCAN key cursor [MATCH pattern] [COUNT count]

Key-value pairs in an iterative hash table.

For more commands, please refer to https://redis.io/commands

4) .Redis commands for list (List) operations

Redis 127.0.0.1 redis 6379 > LPUSH xlosykey redis (integer) 1redis 127.0.0.1 1redis 6379 > LPUSH xlosykey mongodb (integer) 2redis 127.0.0.1 integer 6379 > LPUSH xlosykey mysql (integer) 3redis 127.0.0.1 LRANGE xlosykey 0101) "mysql" 2) "mongodb" 3) "redis"

1 BLPOP key1 [key2] timeout

Move out and get the first element of the list, and if there are no elements in the list, it blocks the list until the wait times out or until a popup element is found.

2 BRPOP key1 [key2] timeout

Move out and get the last element of the list, and if there are no elements in the list, it blocks the list until the wait times out or until a popup element is found.

3 BRPOPLPUSH source destination timeout

Pop a value from the list, insert the pop-up element into another list and return it; if there are no elements in the list, it blocks the list until the wait times out or until a popup element is found.

4 LINDEX key index

Get the elements in the list through the index

5 LINSERT key BEFORE | AFTER pivot value

Insert an element before or after an element in the list

6 LLEN key

Get the list length

7 LPOP key

Move out and get the first element of the list

8 LPUSH key value1 [value2]

Insert one or more values into the list header

9 LPUSHX key value

Insert a value into the existing list header

10 LRANGE key start stop

Gets the elements within the specified range of the list

11 LREM key count value

Remove list element

12 LSET key index value

Set the value of a list element through an index

13 LTRIM key start stop

Trim a list, that is, let the list retain only the elements within the specified range, and all elements that are not within the specified range will be deleted.

14 RPOP key

Remove and get the last element of the list

15 RPOPLPUSH source destination

Remove the last element of the list, add that element to another list and return

16 RPUSH key value1 [value2]

Add one or more values to the list

17 RPUSHX key value

Add values to an existing list

5) .Redis commands for collection (Set) operations

Redis 127.0.0.1 redis 6379 > SADD xlosykey redis (integer) 1redis 127.0.0.1 1redis 6379 > SADD xlosykey mongodb (integer) 1redis 127.0.0.1 1redis 6379 > SADD xlosykey mysql (integer) 1redis 127.0.0.1 integer 6379 > SADD xlosykey mysql (integer) 0redis 127.0.0.1 1redis 6379 > SMEMBERS xlosykey 1) "mysql" 2) "mongodb" 3) "redis"

1 SADD key member1 [member2]

Add one or more members to the collection

2 SCARD key

Gets the number of members of the collection

3 SDIFF key1 [key2]

Returns the difference of all given sets

4 SDIFFSTORE destination key1 [key2]

Returns the difference of all given sets and stores them in destination

5 SINTER key1 [key2]

Returns the intersection of all given sets

6 SINTERSTORE destination key1 [key2]

Returns the intersection of all given collections and stores them in destination

7 SISMEMBER key member

Determine whether the member element is a member of the collection key

8 SMEMBERS key

Returns all members of the collection

9 SMOVE source destination member

Move member elements from the source collection to the destination collection

10 SPOP key

Removes and returns a random element in the collection

11 SRANDMEMBER key [count]

Returns one or more random numbers in the collection

12 SREM key member1 [member2]

Remove one or more members of the collection

13 SUNION key1 [key2]

Returns the union of all given sets

14 SUNIONSTORE destination key1 [key2]

The union of all given collections is stored in the destination collection

15 SSCAN key cursor [MATCH pattern] [COUNT count]

Iterate over the elements in a collection

6) .Redis commands for ordered sets (sorted set) operations

Redis 127.0.0.1 1redis 127.0.0.1 1redis 6379 > ZADD xlosykey 2 mongodb (integer) 1redis 127.0.0.1 1redis 127.0.0.1 1redis 127.0.1) ZADD xlosykey 3 mysql (integer) 0redis 127.0.1) ZADD xlosykey 4 mysql (integer) 0redis 127.0.1) 0redis 127.0.1) "2" 5) "mysql" 6) "4"

1 ZADD key score1 member1 [score2 member2]

Add one or more members to an ordered collection, or update the scores of existing members

2 ZCARD key

Get the number of members of an ordered set

3 ZCOUNT key min max

Calculate the number of members with a specified interval score in an ordered set

4 ZINCRBY key increment member

Add an incremental increment to the score of a specified member in an ordered set

5 ZINTERSTORE destination numkeys key [key...]

Calculates the intersection of one or more given ordered sets and stores the result set in a new ordered set key

6 ZLEXCOUNT key min max

Calculate the number of members in a specified dictionary interval in an ordered set

7 ZRANGE key start stop [WITHSCORES]

Return the ordered set through the index interval to synthesize the members in the specified interval

8 ZRANGEBYLEX key min max [LIMIT offset count]

Returns the members of an ordered set through a dictionary interval

9 ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT]

Returns the members of a specified interval in an ordered set by score

10 ZRANK key member

Returns the index of the specified member in an ordered collection

11 ZREM key member [member...]

Remove one or more members from an ordered set

12 ZREMRANGEBYLEX key min max

Removes all members of a given dictionary interval in an ordered set

13 ZREMRANGEBYRANK key start stop

Removes all members of a given ranking interval in an ordered set

14 ZREMRANGEBYSCORE key min max

Remove all members of a given fraction interval in an ordered set

15 ZREVRANGE key start stop [WITHSCORES]

Returns the members of the specified interval in an ordered set, with the score from high to low by index

16 ZREVRANGEBYSCORE key max min [WITHSCORES]

Returns the members in the specified score range in an ordered set, sorted from high to low

17 ZREVRANK key member

Returns the ranking of the specified members in an ordered set, sorted by decreasing scores (from large to small)

18 ZSCORE key member

Returns the score value of the member in an ordered set

19 ZUNIONSTORE destination numkeys key [key...]

Calculates the union of one or more given ordered sets and stores them in a new key

20 ZSCAN key cursor [MATCH pattern] [COUNT count]

Elements in an iterative ordered set (including element members and element scores)

VII. Publishing and subscribing to Redis

Redis publish subscription (pub/sub) is a mode of message communication: the sender (pub) sends the message and the subscriber (sub) receives the message.

Redis clients can subscribe to any number of channels.

Redis 127.0.0.1 6379 > SUBSCRIBE redisChatReading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "redisChat" 3) (integer) 1

Subscribe to a channel message named "redisChat" and wait for the channel message

Redis 127.0.0.1 1redis 6379 > PUBLISH redisChat "Redis is a great caching technique" (integer) 1redis 127.0.1 1redis > PUBLISH redisChat "Learn redis by xlosy.com" (integer) 1

The subscriber's client displays the following message

1) "message" 2) "redisChat" 3) "Redis is a great caching technique" 1) "message" 2) "redisChat" 3) "Learn redis by xlosy.com"

1 PSUBSCRIBE pattern [pattern...]

Subscribe to one or more channels that match a given pattern.

2 PUBSUB subcommand [argument [argument...]]

View the status of the subscription and publishing system.

3 PUBLISH channel message

Sends the information to the specified channel.

4 PUNSUBSCRIBE [pattern [pattern...]]

Unsubscribe from all channels in a given mode.

5 SUBSCRIBE channel [channel...]

Subscribe to information for a given channel or channels.

6 UNSUBSCRIBE [channel [channel...]]

To unsubscribe from a given channel.

VII. Redis transaction

Redis transactions can execute more than one command at a time with two important guarantees:

Bulk operations are cached in queues before sending EXEC commands.

After receiving the EXEC command, enter the transaction execution, any command execution in the transaction fails, and the rest of the commands are still executed.

During transaction execution, command requests submitted by other clients are not inserted into the transaction execution command sequence.

A transaction goes through the following three stages from start to execution:

Start the business.

Order to join the team.

Execute the transaction.

Redis 127.0.0.1 Mastering in 21 days QUEUEDredis 127.0.0.1 in 6379 > GET book-nameQUEUEDredis 127.0.1 QUEUEDredis 127.0.1 QUEUEDredis 127.0.1 OK2 OK2) Mastering C++ in 21 days 3) (integer) 34) 1) "Mastering Series" 2) "C++" 3) "Programming"

The execution of a single Redis command is atomic, but Redis does not add any mechanism to maintain atomicity on the transaction, so the execution of the Redis transaction is not atomic.

A transaction can be understood as a packaged batch execution script, but a batch instruction is not an atomized operation, and the failure of an intermediate instruction will not cause a rollback of the previously done instruction, nor will it cause subsequent instructions not to be done.

1 DISCARD

Cancels the transaction and discards all commands within the transaction block.

2 EXEC

Execute commands within all transaction blocks.

3 MULTI

Marks the beginning of a transaction block.

4 UNWATCH

Unmonitor all key from the WATCH command.

5 WATCH key [key...]

Monitor one (or more) key, and if the key (or these) is altered by other commands before the transaction is executed, the transaction will be interrupted.

VIII. Redis script

The Redis script uses the Lua interpreter to execute the script. Redis 2.6 supports the Lua environment through built-in support. The common command to execute a script is EVAL.

Redis 127.0.0.1 redis 6379 > EVAL "return {KEYS [1], KEYS [2], ARGV [1], ARGV [2]}" 2 key1 key2 first second1) "key1" 2) "key2" 3) "first" 4) "second"

1 EVAL script numkeys key [key...] Arg [arg...]

Execute the Lua script.

2 EVALSHA sha1 numkeys key [key...] Arg [arg...]

Execute the Lua script.

3 SCRIPT EXISTS script [script...]

Check to see if the specified script has been saved in the cache.

4 SCRIPT FLUSH

Removes all scripts from the script cache.

5 SCRIPT KILL

Kill the currently running Lua script.

6 SCRIPT LOAD script

The script script is added to the script cache, but the script is not executed immediately.

IX. Redis connection

Redis 127.0.0.1 password 6379 > AUTH "password" OKredis 127.0.0.1 OKredis 6379 > PINGPONG

1 AUTH password

Verify that the password is correct

2 ECHO message

Print string

3 PING

Check to see if the service is running

4 QUIT

Close the current connection

5 SELECT index

Switch to the specified database

10. Redis server

Redis 127.0.0.1 6379 > INFO / / displays service related information

1 BGREWRITEAOF

Asynchronously perform an AOF (AppendOnly File) file rewrite operation

2 BGSAVE

Asynchronously save the data of the current database to disk in the background

3 CLIENT KILL [ip:port] [ID client-id]

Close client connection

4 CLIENT LIST

Get a list of client connections to the server

5 CLIENT GETNAME

Get the name of the connection

6 CLIENT PAUSE timeout

Stop running commands from the client within a specified period of time

7 CLIENT SETNAME connection-name

Sets the name of the current connection

8 CLUSTER SLOTS

Get the mapping array of cluster nodes

9 COMMAND

Get an array of Redis command details

10 COMMAND COUNT

Get the total number of Redis commands

11 COMMAND GETKEYS

Gets all the keys for a given command

12 TIME

Returns the current server time

13 COMMAND INFO command-name [command-name...]

Gets the array described by the specified Redis command

14 CONFIG GET parameter

Gets the value of the specified configuration parameter

15 CONFIG REWRITE

Rewrite the redis.conf configuration file specified when starting the Redis server

16 CONFIG SET parameter value

Modify redis configuration parameters without reboot

17 CONFIG RESETSTAT

Reset some statistics in the INFO command

18 DBSIZE

Returns the number of key in the current database

19 DEBUG OBJECT key

Get debugging information for key

20 DEBUG SEGFAULT

Let the Redis service crash

21 FLUSHALL

Delete all key for all databases

22 FLUSHDB

Delete all key of the current database

23 INFO [section]

Get all kinds of information and statistical values of Redis server

24 LASTSAVE

Returns the last time Redis successfully saved data to disk, expressed in UNIX timestamp format

25 MONITOR

Print out the commands received by the Redis server in real time for debugging

26 ROLE

Returns the role to which the master-slave instance belongs

27 SAVE

Save data to hard disk synchronously

28 SHUTDOWN [NOSAVE] [SAVE]

Save data asynchronously to the hard disk and shut down the server

29 SLAVEOF host port

Converts the current server to a slave server (slave server) of the specified server

30 SLOWLOG subcommand [argument]

Manage slow logs for redis

31 SYNC

Internal commands for the copy function (replication)

11. Use redis in java

First, you need to download the driver package, download jedis.jar, and make sure you download the latest driver package.

Include the driver package in your classpath.

Import redis.clients.jedis.Jedis; public class RedisJava {public static void main (String [] args) {/ / connect to the local Redis service Jedis jedis = new Jedis ("localhost"); System.out.println ("connected successfully"); / / check whether the service is running System.out.println ("Service is running:" + jedis.ping ());}}

Operation string

Import redis.clients.jedis.Jedis; public class RedisStringJava {public static void main (String [] args) {/ / connect to the local Redis service Jedis jedis = new Jedis ("localhost"); System.out.println ("connection succeeded"); / / set redis string data jedis.set ("xlosykey", "www.xlosy.com") / / get the stored data and output System.out.println ("redis stored string is:" + jedis.get ("runoobkey"));}}

Redis Java List (list) instance

Import java.util.List;import redis.clients.jedis.Jedis; public class RedisListJava {public static void main (String [] args) {/ / connect to the local Redis service Jedis jedis = new Jedis ("localhost"); System.out.println ("connected successfully"); / / store data in the list jedis.lpush ("site-list", "xlosy") Jedis.lpush ("site-list", "Google"); jedis.lpush ("site-list", "Taobao"); / / get the stored data and output List list = jedis.lrange ("site-list", 0,2); for (int item0; I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report