当前位置:网站首页>What does redis do? Redis often practices grammar every day
What does redis do? Redis often practices grammar every day
2022-07-03 23:59:00 【nezha】
Catalog
One 、 Baidu Encyclopedia
redis It's a key-value The storage system . and Memcached similar , It supports storage value There are more types , Include string( character string )、list( Linked list )、set( aggregate )、zset(sorted set -- Ordered set ) and hash( Hash type ). These data types support push/pop、add/remove And take intersection, union and difference sets and more abundant operations , And these operations are atomic . On this basis ,redis Support various sorts of sorting . And memcached equally , To ensure efficiency , The data is cached in memory . The difference is redis Periodically, updated data is written to disk or changes are written to an appended log file , And on this basis to achieve master-slave( Master-slave ) Sync .
Redis Is a high-performance key-value database . redis Appearance , A lot of compensation memcached This kind of key/value Insufficient storage , In the department The situation can be a good complement to the relational database . It provides Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang Such as the client , Easy to use .
Redis Support master-slave synchronization . Data can be synchronized from the master server to any number of slaves , A slave server can be the master server associated with other slaves . This makes Redis Single-layer tree replication can be performed . The disk can write to the data intentionally or unintentionally . Due to the full implementation of the release / Subscribe mechanism , Enables trees to be synchronized anywhere from the database , Subscribe to a channel and receive a complete record of message publication from the master server . Synchronization helps with scalability and data redundancy for read operations .
Two 、Redis download

3、 ... and 、Linux Install in Redis
1、 Upload 、 decompression
Redis Generally installed in Linux In the environment , Turn on virtual machine , adopt xftp take redis Upload the compressed package to Linux The server , And unpack it .
2、 modify redis.conf The configuration file , Make it start in the background

Four 、Java call redis
1、 Import pom
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
2、 To write Java Main method
call Redis Medium ping Method , Surprised and abnormal :
(1) At first, I thought it was a firewall problem , Later by checking redis State discovery IP Wrong address , Should not be 127.0.0.1
(2) modify redis.conf
Be careful : It should be noted that you are modifying redis.conf when ,① Note out bind 127.0.0.1;② The local access protection mode needs to be set to no
3、 Execute the main method again , Successful implementation !

5、 ... and 、 Five data type code examples
package com.guor.redis;
import redis.clients.jedis.Jedis;
import java.util.List;
import java.util.Set;
public class JedisTest01 {
public static void main(String[] args) {
test05();
}
private static void test01(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
String value = jedis.ping();
System.out.println(value);
// add to
jedis.set("name","GooReey");
// obtain
String name = jedis.get("name");
System.out.println(name);
jedis.set("age","30");
jedis.set("city","dalian");
// Get all of key
Set<String> keys = jedis.keys("*");
for(String key : keys){
System.out.println(key+" --> "+jedis.get(key));
}
// Join multiple key and value
jedis.mset("name1","zs","name2","ls","name3","ww");
List<String> mget = jedis.mget("name1", "name2");
System.out.println(mget);//[zs, ls]
}
//list
private static void test02(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
jedis.lpush("key1","01","02","03");
List<String> values = jedis.lrange("key1",0,-1);
System.out.println(values);//[03, 02, 01]
}
//set
private static void test03(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
jedis.sadd("username","zs","ls","ww");
Set<String> names = jedis.smembers("username");
System.out.println(names);//[ww, zs, ls]
}
//hash
private static void test04(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
jedis.hset("users","age", "20");
String hget = jedis.hget("users","age");
System.out.println(hget);
}
//zset
private static void test05(){
Jedis jedis = new Jedis("192.168.194.131", 6379);
jedis.zadd("china",100d,"shanghai");
Set<String> names = jedis.zrange("china",0,-1);
System.out.println(names);//[shanghai]
}
}
6、 ... and 、 Mobile phone verification code function code example
package com.guor.redis;
import redis.clients.jedis.Jedis;
import java.util.Random;
public class PhoneCode {
public static void main(String[] args) {
verifyCode("10086");//795258
getRedisCode("10086","795258");//success.
}
//1、 Generate 6 Digit verification code
public static String getCode(){
Random random = new Random();
String code = "";
for (int i = 0; i < 6; i++) {
int rand = random.nextInt(10);
code += rand;
}
return code;//849130
}
//2、 Each phone can only send three times a day , Verification code in redis in , Set expiration time
public static void verifyCode(String phone){
Jedis jedis = new Jedis("192.168.194.131", 6379);
// Splicing key
// The number of times a cell phone sends key
String countKey = "VerifyCode" + phone + ":count";
// Verification Code key
String codeKey = "VerifyCode" + phone + ":code";
// Each phone can only send three times a day
String count = jedis.get(countKey);
if(count == null){
// Set expiration time
jedis.setex(countKey,24*60*60,"1");
}else if(Integer.parseInt(count)<=2){
// Number of times sent +1
jedis.incr(countKey);
}else if(Integer.parseInt(count)>2){
System.out.println(" More than three times today ");
jedis.close();
}
String vCode = getCode();
jedis.setex(codeKey,120,vCode);
jedis.close();
}
//3、 Verification code verification
public static void getRedisCode(String phone, String code){
// from redis Get the verification code from
Jedis jedis = new Jedis("192.168.194.131", 6379);
// Verification Code key
String codeKey = "VerifyCode" + phone + ":code";
String redisCode = jedis.get(codeKey);
if(redisCode.equals(code)){
System.out.println("success.");
}else{
System.out.println("error");
}
jedis.close();
}
}

When more than three times :
7、 ... and 、SpringBoot Integrate Redis
1、 Construction works , introduce pom

<?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 https://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.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.guor</groupId>
<artifactId>redisspringboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>redisspringboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.4.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、 Configuration class
(1)application.properties
# Redis Database index ( The default is 0)
spring.redis.database=0
# Redis Server address
spring.redis.host=192.168.194.131
# Redis Server connection port
spring.redis.port=6379
# Redis Server connection password ( The default is empty. )
spring.redis.password=
# Maximum number of connections in connection pool ( Use a negative value to indicate that there is no limit )
spring.redis.jedis.pool.max-active=20
# Connection pool maximum blocking wait time ( Use a negative value to indicate that there is no limit )
spring.redis.jedis.pool.max-wait=-1
# The maximum free connection in the connection pool
spring.redis.jedis.pool.max-idle=10
# The smallest free connection in the connection pool
spring.redis.jedis.pool.min-idle=0
# Connection timeout ( millisecond )
spring.redis.timeout=1000
(2)RedisConfig
package com.guor.redisspringboot.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;
@EnableCaching
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key use String How to serialize
template.setKeySerializer(stringRedisSerializer);
// hash Of key Also used String How to serialize
template.setHashKeySerializer(stringRedisSerializer);
// value The serialization method adopts jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash Of value The serialization method adopts jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
/** * be based on SpringBoot2 Yes RedisCacheManager Custom configuration for * @param redisConnectionFactory * @return */
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// Initialize a RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
// Set up CacheManager The value of is serialized in json serialize
RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer);
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
// Set the default expiration period to 1 God
defaultCacheConfig.entryTtl(Duration.ofDays(1));
// initialization RedisCacheManager
return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
}
3、 Control class test
package com.guor.redisspringboot.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping
public String getRedis(){
redisTemplate.opsForValue().set("name","zs");
String name = (String) redisTemplate.opsForValue().get("name");
return name;
}
}

边栏推荐
- Maxwell equation and Euler formula - link
- How to make recv have a little temper?
- [note] glide process and source code analysis
- Research Report on the scale prediction of China's municipal engineering industry and the prospect of the 14th five year plan 2022-2028
- Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
- 2/14 (regular expression, sed streaming editor)
- Axure resources and prototype tool Axure RP 9 download
- It is forbidden to splice SQL in code
- 2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
- Smart fan system based on stm32f407
猜你喜欢

2022 free examination questions for hoisting machinery command and hoisting machinery command theory examination
![[2021]NeRF in the Wild: Neural Radiance Fields for Unconstrained Photo Collections](/img/c6/3dc7d01600f6713afdbb4cf3df5238.jpg)
[2021]NeRF in the Wild: Neural Radiance Fields for Unconstrained Photo Collections

Kubedl hostnetwork: accelerating the efficiency of distributed training communication

Alibaba cloud container service differentiation SLO hybrid technology practice

Pytorch learning notes 5: model creation

Private project practice sharing populate joint query in mongoose makes the template unable to render - solve the error message: syntaxerror: unexpected token r in JSON at

BBS forum recommendation

Recommendation of knowledge base management system

Idea integrates Microsoft TFs plug-in
![[PHP basics] cookie basics, application case code and attack and defense](/img/7c/551b79fd5dd8a411de85c800c3a034.jpg)
[PHP basics] cookie basics, application case code and attack and defense
随机推荐
The interviewer's biggest lie to deceive you, bypassing three years of less struggle
Op amp related - link
2/14 (regular expression, sed streaming editor)
炒股开户佣金优惠怎么才能获得,网上开户安全吗
Idea a method for starting multiple instances of a service
[leetcode] interview question 17.08 Circus tower
Selenium check box
Selenium library 4.5.0 keyword explanation (III)
Solve the problem that the kaggle account registration does not display the verification code
Fluent learning (5) GridView
"Learning notes" recursive & recursive
Entropy and full connection layer
Double efficiency. Six easy-to-use pychar plug-ins are recommended
URL (data:image/png; Base64, ivborw0k... Use case
Gossip about redis source code 73
AI Challenger 2018 text mining competition related solutions and code summary
BBS forum recommendation
Subgraph isomorphism -subgraph isomorphism
Gossip about redis source code 78
2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination