当前位置:网站首页>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;
}
}

边栏推荐
- What are the securities companies with the lowest Commission for stock account opening? Would you recommend it? Is it safe to open an account on your mobile phone
- 炒股開戶傭金優惠怎麼才能獲得,網上開戶安全嗎
- Several ways to set up a blog locally [attach relevant software download links]
- Selenium library 4.5.0 keyword explanation (I)
- P1656 bombing Railway
- [MySQL] sql99 syntax to realize multi table query
- ISBN number
- EPF: a fuzzy testing framework for network protocols based on evolution, protocol awareness and coverage guidance
- FPGA tutorial and Allegro tutorial - link
- Comment obtenir une commission préférentielle pour l'ouverture d'un compte en bourse? Est - ce que l'ouverture d'un compte en ligne est sécurisée?
猜你喜欢

Kubedl hostnetwork: accelerating the efficiency of distributed training communication

Detailed explanation of the relationship between Zhongtai, wechat and DDD

How to write a good title of 10w+?

2022 examination of safety production management personnel of hazardous chemical production units and examination skills of safety production management personnel of hazardous chemical production unit

MySQL 8.0.12 error: error 2013 (HY000): lost connection to MySQL server during query

A method to solve Bert long text matching

Introducing Software Testing

What is the Valentine's Day gift given by the operator to the product?

The interviewer's biggest lie to deceive you, bypassing three years of less struggle

Design of logic level conversion in high speed circuit
随机推荐
Detailed explanation of the relationship between Zhongtai, wechat and DDD
2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
Distributed transaction -- middleware of TCC -- selection / comparison
Cgb2201 preparatory class evening self-study and lecture content
A treasure open source software, cross platform terminal artifact tabby
Fluent learning (5) GridView
2020.2.14
Regular expressions and text processors for shell programming
Alibaba cloud container service differentiation SLO hybrid technology practice
炒股开户佣金优惠怎么才能获得,网上开户安全吗
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
NLP pre training technology development
D28:maximum sum (maximum sum, translation)
C # basic knowledge (3)
[BSP video tutorial] stm32h7 video tutorial phase 5: MDK topic, system introduction to MDK debugging, AC5, AC6 compilers, RTE development environment and the role of various configuration items (2022-
The difference between single power amplifier and dual power amplifier
Suggestions for improving code quality
It is the most difficult to teach AI to play iron fist frame by frame. Now arcade game lovers have something
Gossip about redis source code 81
How to make recv have a little temper?