当前位置:网站首页>Basic use of redis
Basic use of redis
2022-07-06 11:02:00 【Bolus acidophilus】
List of articles
Redis Basics
- Redis introduction
- Redis data type
- Redis Common commands
- stay Java In the operation Redis
1. Preface
1.1 What is? Redis
Redis It's based on Memory Of key-value Structure database .Redis It is the most widely used storage Middleware in the field of Internet technology , It is 「Remote Dictionary Service」 An acronym for , That is to say 「 Remote Dictionary Service 」.
- Based on memory storage , High reading and writing performance
- Suitable for storing hotspot data ( Hot products 、 information 、 Journalism )
- Widely used in enterprises
1.2 Use Redis What can be done
- Data caching
- Message queue
- Registry Center
- Publish subscribe
2. Redis introduction
2.1 Redis brief introduction
Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. Translated into :Redis Is an open source in-memory data structure storage system , It can be used as : database 、 Caching and message middleware .
Official website :https://redis.io
Redis Yes, it is C An open source high performance key value pair for language development (key-value) database , The data provided by the government can reach 100000+ Of QPS( Number of queries per second ). It stores value There are many types , Also known as structured NoSql database .
NoSql(Not Only SQL), not only SQL, Generally speaking Non relational database .NoSql Databases are not meant to replace relational databases , It's a supplement to relational databases .
Relational database (RDBMS):
- Mysql
- Oracle
- DB2
- SQLServer
Non relational database (NoSql):
- Redis
- Mongo db
- MemCached
2.2 Redis Download and install
2.2.1 Redis download
Redis Installation package is divided into windows Version and Linux edition :
- Windows Version download address :https://github.com/microsoftarchive/redis/releases
- Linux Version download address : https://download.redis.io/releases/
2.2.2 Redis install
1) stay Linux Install in Redis**
stay Linux System installation Redis step :
- take Redis Upload the installation package to Linux
- Unzip the installation package , command :
tar -zxvf redis-4.0.0.tar.gz -C /usr/local
- install Redis Dependent environment of gcc, command :
yum install gcc-c++
- Get into /usr/local/redis-4.0.0, Compile , command :
make
- Get into redis Of src Directory for installation , command :
make install
Description of key documents after installation :
/usr/local/redis-4.0.0/src/redis-server:Redis Service startup script
/usr/local/redis-4.0.0/src/redis-cli:Redis Client script
/usr/local/redis-4.0.0/redis.conf:Redis The configuration file
2) stay Windows Install in Redis**
Redis Of Windows Version belongs to green software , Decompress directly and use , After decompression, the directory structure is as follows :
2.3 Redis Service start and stop
1)Linux Start and stop in the system Redis
perform Redis Service startup script file cd /usr/local/redis-4.0.0/src
>./redis-server
:
From the startup log, you can see ,Redis The default port number is 6379.
Ctrl + C stop it Redis service
adopt redis-cli You can connect to local Redis service , By default, you can connect successfully without authentication .
After exiting the client, you can enter exit perhaps quit command .
2)Windows Start and stop in the system Redis
Windows Start in the system Redis, Direct double click redis-server.exe You can start Redis service ,redis The default port number of the service is 6379
Ctrl + C stop it Redis service
double-click redis-cli.exe You can start Redis client , The default connection is local Redis service , And you can connect successfully without authentication .
After exiting the client, you can enter exit perhaps quit command .
Flash back : Open in the current directory CMD, Input
redis-server.exe redis.windows.conf
If you still report the following error :
Creating Server TCP listening socket 127.0.0.1:6379: bind: No error
Enter the following commands in order to connect successfully
redis-cli.exe
shutdown
exit
redis-server.exe redis.windows.conf
2.4 Redis The configuration file
By default Redis After startup, it runs in the foreground , And the client can connect to... Without a password Redis service . If Redis After the service is started, it runs in the background , At the same time, the client can only connect to Redis service .
Be careful :Windows Version of Redis Background running is not supported .
Need modification Redis Configuration file for :
- Linux In the system Redis The configuration file :REDIS_HOME/redis.conf
- Windows In the system Redis The configuration file :REDIS_HOME/redis.windows.conf
- By modifying the Redis The configuration file can be configured as follows :
- Set up Redis The service runs in the background
In the configuration file daemonize Configuration item changed to yes, The default value is no.
- Set up Redis The service runs in the background
- Set up Redis Service password
In the configuration file # requirepass foobared Uncomment the configuration item , The default is annotation status .[foobared] Is password .
- Set up Redis Service password
- Setting allows clients to connect remotely Redis service
Redis By default, the service can only be connected locally by the client , Do not allow clients to connect remotely . In the configuration file bind 127.0.0.1 Comment out the configuration item .
- Setting allows clients to connect remotely Redis service
interpretative statement :
Redis In profile # Notation
Redis The configuration item in the configuration file cannot be preceded by a space , You need to write in the top box
daemonize: Used to specify redis Do you want to start it as a daemonic thread , Set to yes when , On behalf of the open daemons mode . In this mode ,redis Will run in the background
requirepass: Set up Redis Connection password for
bind: If you specify bind, It indicates that only the network card from the specified network card is allowed Redis request . If not specified , It means that you can accept from any network card Redis request .
Be careful : You need to restart after modifying the configuration file Redis Service configuration takes effect , And start up Redis The specified configuration file that needs to be displayed during service :
1)Linux Start in Redis service
# Get into Redis The installation directory
cd /usr/local/redis-4.0.0
# start-up Redis service , Specify the configuration file to use
./src/redis-server ./redis.conf
2)Windows Start in Redis service
because Redis Authentication is enabled in the configuration file , That is, the client needs to provide a password when connecting , At this point, the client connection mode changes to :
interpretative statement :
-h: Specify connected Redis Service ip Address
-p: Specify connected Redis The port number of the service
-a: Specify connected Redis Password for the service
3. Redis data type
3.1 Introduce
Redis What's stored is key-value Structured data , among key It's a string type ,value Yes 5 Common data types :
- character string string: Normal string , Commonly used
- Hash hash: Suitable for storing objects
- list list: Sort by insertion order , Can have repeating elements
- aggregate set: unordered set , There are no repeating elements
- Ordered set sorted set / zset: Each element in the collection is associated with a score (score), Sort according to the score , There are no repeating elements
3.2 Redis 5 Two common data types
4. Redis Common commands
4.1 character string string Operation command
Redis Common commands of string type in :
- SET key value Set the specified key Value
- GET key Get specified key Value
- SETEX key seconds value Set the specified key Value , And will key The expiration time of is set to seconds second
- SETNX key value Only in key Set when not present key Value
More commands can be found in Redis Chinese net :https://www.redis.net.cn
4.2 Hash hash Operation command
Redis hash It's a string Type of field and value Mapping table ,hash Ideal for storing objects , Common commands :
- HSET key field value Hash table key In the field field The value of the set value
- HGET key field Gets the value of the specified field stored in the hash table
- HDEL key field Deletes the specified field stored in the hash table
- HKEYS key Get all fields in the hash table
- HVALS key Get all values in hash table
- HGETALL key Gets the specified in the hash table key All fields and values of
4.3 list list Operation command
Redis List is a simple list of strings , Sort by insertion order , Common commands :
- LPUSH key value1 [value2] Insert one or more values into the list header
- LRANGE key start stop Get the elements in the specified range of the list
- RPOP key Remove and get the last element of the list
- LLEN key Get list length
- BRPOP key1 [key2 ] timeout Move out and get the last element of the list , If there are no elements in the list, the list will be blocked until it waits for super Or until a pop-up element is found
4.4 aggregate set Operation command
Redis set yes string Unordered collection of type . Collection members are unique , This means that duplicate data cannot appear in the collection , Common commands :
- SADD key member1 [member2] Add one or more members to the collection
- SMEMBERS key Returns all members of the collection
- SCARD key Get the number of members of the collection
- SINTER key1 [key2] Returns the intersection of a given set
- SUNION key1 [key2] Returns the union of all given sets
- SDIFF key1 [key2] Returns the difference set of all given sets
- SREM key member1 [member2] Remove one or more members of the collection
4.5 Ordered set sorted set Operation command
Redis sorted set An ordered set is string Collection of type elements , And duplicate members are not allowed . Each element is associated with a double Score of type (score) .redis It is through scores that the members of the set are sorted from small to large . Members of an ordered set are unique , But scores can be repeated .
Common commands :
- ZADD key score1 member1 [score2 member2] Add one or more members... To an ordered collection , Or update existing members fraction
- ZRANGE key start stop [WITHSCORES] Return the members in the specified interval in the ordered set through the index interval
- ZINCRBY key increment member Add the increment... To the score of the specified member in the ordered set increment
- ZREM key member [member …] Remove one or more members of an ordered collection
4.6 General Command
Redis General commands in , Mainly aimed at key Related commands for operation :
- KEYS pattern Find all that match the given pattern ( pattern) Of key
- EXISTS key Check the given key Whether there is
- TYPE key return key The type of value stored
- TTL key Return to a given key The remaining lifetime of (TTL, time to live), In seconds
- DEL key This command is used in key Existence is deletion key
5. stay Java In the operation Redis
5.1 Introduce
Need to use Redis Of Java client , It's like using JDBC operation MySQL The database is the same .
Redis Of Java Many clients , There are three official recommendations :
- Jedis
- Lettuce
- Redisson
Spring Yes Redis The client is integrated , Provides Spring Data Redis, stay Spring Boot The corresponding... Is also provided in the project Starter, namely spring-boot-starter-data-redis.
5.2 Java Native Jedis Client operation Redis
Jedis yes Redis Of Java Version of the client implementation .
maven coordinate :
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
Use Jedis operation Redis Steps for :
- Get the connection
- Perform the operation
- Close the connection
Sample code :
import org.junit.Test;
import redis.clients.jedis.Jedis;
import java.util.Set;
/** * Use Jedis operation Redis */
public class JedisTest {
@Test
public void testRedis(){
//1 Get the connection
Jedis jedis = new Jedis("localhost",6379);
//2 Perform specific operations
jedis.set("username","xiaoming");
String value = jedis.get("username");
System.out.println(value);
//jedis.del("username");
jedis.hset("myhash","addr","bj");
String hValue = jedis.hget("myhash", "addr");
System.out.println(hValue);
Set<String> keys = jedis.keys("*");
for (String key : keys) {
System.out.println(key);
}
//3 Close the connection
jedis.close();
}
}
5.3 Spring Data Redis
5.3.1 Introduce
Spring Data Redis yes Spring Part of , Provided in Spring The application can be accessed through simple configuration Redis service , Yes Redis The underlying development package is highly encapsulated . stay Spring In the project , have access to Spring Data Redis To simplify the Redis operation .
website :https://spring.io/projects/spring-data-redis
maven coordinate :
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.4.8</version>
</dependency>
Spring Boot The corresponding is provided Starter,maven coordinate :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Spring Data Redis Provides a highly encapsulated class :RedisTemplate, in the light of Jedis There are a lot of api It is classified and packaged , Encapsulate the same type of operation as operation Interface , The specific classification is as follows :
- ValueOperations: Simple K-V operation
- SetOperations:set Type data operation
- ZSetOperations:zset Type data operation
- HashOperations: in the light of hash Type of data operation
- ListOperations: in the light of list Type of data operation
5.3.2 Usage mode
Environment building
First step : establish maven project springdataredis_demo, To configure pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/>
</parent>
<groupId>com.itheima</groupId>
<artifactId>springdataredis_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.5</version>
</plugin>
</plugins>
</build>
</project>
The second step : Write the startup class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
The third step : To configure application.yml
spring:
application:
# Name of application , Optional
name: springdataredis_demo
#Redis Related configuration
redis:
host: localhost
port: 6379
#password: 123456
database: 0 # The operation is 0 The database
jedis:
#Redis Connection pool configuration
pool:
max-active: 8 # maximum connection
max-wait: 1ms # Connection pool maximum blocking wait time
max-idle: 4 # The maximum free connection in the connection pool
min-idle: 0 # The smallest free connection in the connection pool
interpretative statement :
spring.redis.database: Specify the use of Redis Which database ,Redis After the service is started, there are... By default 16 A database , The numbers are from 0 To 15.
It can be modified by Redis Configuration file to specify the number of databases .
Step four : Provide configuration class
The current configuration class is not required , because Spring Boot The frame will be assembled automatically RedisTemplate object , But by default key The serializer is JdkSerializationRedisSerializer, Cause save to Redis There is a difference between the later data and the original data
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/** * Redis Configuration class */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
// default Key The serializer is :JdkSerializationRedisSerializer
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
}
Step five : Provide test classes
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringDataRedisTest {
@Autowired
private RedisTemplate redisTemplate;
}
Operation string type data
/** * operation String Type data */
@Test
public void testString(){
// Store value
redisTemplate.opsForValue().set("city123","beijing");
// Value
String value = (String) redisTemplate.opsForValue().get("city123");
System.out.println(value);//beijing
// Store value , Also set expiration time
redisTemplate.opsForValue().set("key1","value1",10l, TimeUnit.SECONDS);//false
// Store value , If it exists, no action will be taken
Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("city1234", "nanjing");
System.out.println(aBoolean);
}
Operate on Hash type data
/** * operation Hash Type data */
@Test
public void testHash(){
HashOperations hashOperations = redisTemplate.opsForHash();
// Store value
hashOperations.put("002","name","xiaoming");
hashOperations.put("002","age","20");
hashOperations.put("002","address","bj");
// Value
String age = (String) hashOperations.get("002", "age");
System.out.println(age);//20
// get hash All fields in the structure
Set keys = hashOperations.keys("002");
for (Object key : keys) {
System.out.println(key);
//name
//age
//address
}
// get hash All values in the structure
List values = hashOperations.values("002");
for (Object value : values) {
System.out.println(value);
//xiaoming
//20
//bj
}
}
Operation list type data
/** * operation List Data of type */
@Test
public void testList(){
ListOperations listOperations = redisTemplate.opsForList();
// Store value
listOperations.leftPush("mylist","a");
listOperations.leftPushAll("mylist","b","c","d");
// Value
List<String> mylist = listOperations.range("mylist", 0, -1);
for (String value : mylist) {
System.out.println(value);
//d、c、b、a
}
// Get the list length llen
Long size = listOperations.size("mylist");
int lSize = size.intValue();
for (int i = 0; i < lSize; i++) {
// Outgoing queue
String element = (String) listOperations.rightPop("mylist");
System.out.println(element);
//a、b、c、d
}
}
Operation set type data
/** * operation Set Data of type */
@Test
public void testSet(){
SetOperations setOperations = redisTemplate.opsForSet();
// Store value
setOperations.add("myset","a","b","c","a");
// Value
Set<String> myset = setOperations.members("myset");
for (String o : myset) {
System.out.println(o);
//b、a、c
}
// Delete members
setOperations.remove("myset","a","b");
// Value
myset = setOperations.members("myset");
for (String o : myset) {
System.out.println(o);
//c
}
}
Operate on ordered collection type data
/** * operation ZSet Data of type */
@Test
public void testZset(){
ZSetOperations zSetOperations = redisTemplate.opsForZSet();
// Store value
zSetOperations.add("myZset","a",10.0);
zSetOperations.add("myZset","b",11.0);
zSetOperations.add("myZset","c",12.0);
zSetOperations.add("myZset","a",13.0);
// Value
Set<String> myZset = zSetOperations.range("myZset", 0, -1);
for (String s : myZset) {
System.out.println(s);
//b、c、a
}
// Revise the score
zSetOperations.incrementScore("myZset","b",20.0);
// Value
myZset = zSetOperations.range("myZset", 0, -1);
for (String s : myZset) {
System.out.println(s);
//c、a、b
}
// Delete members
zSetOperations.remove("myZset","a","b");
// Value
myZset = zSetOperations.range("myZset", 0, -1);
for (String s : myZset) {
System.out.println(s);
//c
}
}
General operation
/** * General operation , It can be operated for different data types */
@Test
public void testCommon(){
// obtain Redis All of the key
Set<String> keys = redisTemplate.keys("*");
for (String key : keys) {
System.out.println(key);
//myZset、myset、myset
}
// Judge a certain key Whether there is
Boolean itcast = redisTemplate.hasKey("itcast");
System.out.println(itcast);//false
// Delete the specified key
redisTemplate.delete("myZset");
// Get specified key Corresponding value Data type of
DataType dataType = redisTemplate.type("myset");
System.out.println(dataType.name());//SET
}
边栏推荐
- CSDN问答模块标题推荐任务(二) —— 效果优化
- MySQL other hosts cannot connect to the local database
- [recommended by bloggers] C MVC list realizes the function of adding, deleting, modifying, checking, importing and exporting curves (with source code)
- CSDN问答模块标题推荐任务(一) —— 基本框架的搭建
- 一键提取pdf中的表格
- JDBC原理
- 1. Mx6u learning notes (VII): bare metal development (4) -- master frequency and clock configuration
- [untitled]
- Water and rain condition monitoring reservoir water and rain condition online monitoring
- Csdn-nlp: difficulty level classification of blog posts based on skill tree and weak supervised learning (I)
猜你喜欢
CSDN-NLP:基于技能树和弱监督学习的博文难度等级分类 (一)
Copie maître - esclave MySQL, séparation lecture - écriture
CSDN markdown editor
Windows cannot start the MySQL service (located on the local computer) error 1067 the process terminated unexpectedly
MySQL20-MySQL的数据目录
[Li Kou 387] the first unique character in the string
MySQL21-用户与权限管理
C language advanced pointer Full Version (array pointer, pointer array discrimination, function pointer)
连接MySQL数据库出现错误:2059 - authentication plugin ‘caching_sha2_password‘的解决方法
Generate PDM file from Navicat export table
随机推荐
CSDN问答模块标题推荐任务(一) —— 基本框架的搭建
[leectode 2022.2.13] maximum number of "balloons"
csdn-Markdown编辑器
Did you forget to register or load this tag 报错解决方法
Swagger、Yapi接口管理服务_SE
[ahoi2009]chess Chinese chess - combination number optimization shape pressure DP
frp内网穿透那些事
Just remember Balabala
报错解决 —— io.UnsupportedOperation: can‘t do nonzero end-relative seeks
CSDN question and answer module Title Recommendation task (I) -- Construction of basic framework
Mysql24 index data structure
Global and Chinese markets for aprotic solvents 2022-2028: Research Report on technology, participants, trends, market size and share
【博主推荐】asp.net WebService 后台数据API JSON(附源码)
MySQL20-MySQL的数据目录
NPM an error NPM err code enoent NPM err syscall open
MySQL flush operation
Copy constructor template and copy assignment operator template
MySQL21-用户与权限管理
Invalid default value for 'create appears when importing SQL_ Time 'error reporting solution
CSDN question and answer module Title Recommendation task (II) -- effect optimization