当前位置:网站首页>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;
}
}
边栏推荐
- Selenium library 4.5.0 keyword explanation (4)
- IO flow principle and classification
- 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
- leetcode-43. String multiplication
- 【leetcode】374. Guess the size of the number
- ITK learning notes (VII) the position of ITK rotation direction remains unchanged
- Op amp related - link
- Social network analysis -social network analysis
- Detailed explanation of the relationship between Zhongtai, wechat and DDD
- "Learning notes" recursive & recursive
猜你喜欢
[Happy Valentine's day] "I still like you very much, like sin ² a+cos ² A consistent "(white code in the attached table)
How to solve the "safe startup function prevents the operating system from starting" prompt when installing windows10 on parallel desktop?
2022 t elevator repair registration examination and the latest analysis of T elevator repair
Design of logic level conversion in high speed circuit
ESP Arduino playing with peripherals (V) basic concept of interrupt and timer interrupt
Alibaba cloud container service differentiation SLO hybrid technology practice
What is the Valentine's Day gift given by the operator to the product?
Iclr2022: how does AI recognize "things I haven't seen"?
JDBC Technology
It is forbidden to splice SQL in code
随机推荐
2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
No qualifying bean of type ‘com. netflix. discovery. AbstractDiscoveryClientOptionalArgs<?>‘ available
How to make recv have a little temper?
股票开户最低佣金炒股开户免费,网上开户安全吗
网上的低佣金链接安全吗?招商证券怎么开户?
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?
MySQL is installed as a Windows Service
ESP Arduino playing with peripherals (V) basic concept of interrupt and timer interrupt
Fudan 961 review
D23:multiple of 3 or 5 (multiple of 3 or 5, translation + solution)
How can I get the Commission discount of stock trading account opening? Is it safe to open an account online
Zipper table in data warehouse (compressed storage)
Analysis of refrigeration and air conditioning equipment operation in 2022 and examination question bank of refrigeration and air conditioning equipment operation
Research Report on the scale prediction of China's municipal engineering industry and the prospect of the 14th five year plan 2022-2028
What is the difference between NFT, SFT and dnft? How to build NFT platform applications?
How to write a good title of 10w+?
Fluent learning (4) listview
Tencent interview: can you find the number of 1 in binary?
What is the Valentine's Day gift given by the operator to the product?
Gossip about redis source code 73