redis的簡單使用

1.Redis安裝

  • Redis下載

官網下載

  • 將壓縮包上傳到Linux伺服器上

/opt 目錄下

  • 解壓壓縮文件

tar -zxvf redis-6.2.3.tar.gz

  • 安裝GCC編譯器

yum install -y gcc

  • 查看GCC版本

gcc --version

  • 進入解壓後的redis文件夾

cd /opt/redis-6.2.3

  • 在redis-6.2.3目錄下執行make命令
  • 在redis-6.2.3目錄下執行make install命令
  • 若指定安裝目錄,可將上兩步替換為以下命令,將安裝目錄修改為自己的

make PREFIX=/usr/local/redis install

  • 默認安裝目錄

/usr/local/bin

 

Redis配置文件詳解

2.Redis啟動

  • 前台啟動(不推薦使用)

cd /usr/local/bin

redis-server

  • 後台啟動
    • 拷貝一份redis.conf到其他目錄

cp /opt/redis-6.2.3/redis.conf /etc/redis.conf

    • 後台啟動設置redis.conf的daemonize值
    • vi /etc/redis.conf
    • no改成yes
    • 若用阿里雲安裝的redis,必須設置密碼,不然會被挖礦
    • 修改配置文件,設置requirepass值,即密碼值

requirepass xxx

    • redis啟動

cd /usr/local/bin

redis-server /etc/redis.conf

    • 客戶端訪問
    • 無密碼

redis-cli

    • 有密碼

redis-cli -a 密碼

或者使用redis-cli進入redis後,使用auth “密碼” 認證

    • redis關閉

redis-cli shutdown

3.Redis鍵(key)操作

set k1 a —>key:k1 ; value:a

set k2 b

  • keys * 查看當前庫所有key
  • exists key 判斷某個key是否存在 –>exists k1
  • type key 查看你的key是什麼類型 –>type k1
  • del key 刪除指定的key數據 –>del k1
  • unlink key根據value選擇非阻塞刪除僅將keys從keyspace元數據中刪除,真正的刪除會在後續非同步操作。
  • expire key 10 10秒鐘:為給定的key設置過期時間 –>expire k2 10
  • ttl key 查看還有多少秒過期,-1表示永不過期,-2表示已過期 –>ttl k2
  • flushdb 清空當前庫

4 .設置redis的密碼

     :config set requirpass 密碼

       驗證密碼:auth 密碼

5:jedis操作redis:

導入依賴:

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>

連接不上redis的操作步驟:

修改你的redis啟動配置文件redis.conf

①找到 bind 127.0.0.1 ,注釋掉

②修改 protected-mode ,改為no

③(如果需要添加密碼)添加 requirepass 你的密碼

④開放訪問埠6379

⑤第四步不會的話,可以關防火牆。

暫時關閉防火牆:systemctl stop firewalld
測試:

Jedis jedis = new Jedis("192.168.219.130",6379);
//測試
String ping = jedis.ping();
System.out.println(ping);

redis的一些操作用java實現:

@Test
public void test1() {
Jedis jedis = new Jedis("192.168.219.130", 6379);

//添加
jedis.set("name","luck");
//獲取
String name = jedis.get("name");
//設置多個key value
jedis.mset("k1","v1","k2","v2");
List<String> mget = jedis.mget("k1", "k2");
for (String s : mget) {
System.out.println(s);
}
System.out.println(name);
Set<String> keys = jedis.keys("*");
for (String key : keys) {
System.out.println(key);
}
}
//操作list
@Test
public void test2() {
Jedis jedis = new Jedis("192.168.219.130", 6379);
jedis.lpush("key1","luck","tom","marry");
List<String> key1 = jedis.lrange("key1", 0, -1);
System.out.println(key1);
}
//操作set
@Test
public void test3() {
Jedis jedis = new Jedis("192.168.219.130", 6379);
//如果只有有name了,就會報錯
jedis.sadd("name","luck","jack");
Set<String> name = jedis.smembers("name");
System.out.println(name);
}
//操作hash
@Test
public void test4() {
Jedis jedis = new Jedis("192.168.219.130", 6379);
jedis.hset("users","age","20");
String hget = jedis.hget("users", "age");
System.out.println(hget);
}
//操作zset
@Test
public void test5() {
Jedis jedis = new Jedis("192.168.219.130", 6379);
jedis.zadd("china",100,"beijing");
Set<String> china = jedis.zrange("china", 0, -1);
System.out.println(china);
}

6:jedis模擬驗證碼發送

輸入手機號,點擊發送後隨機生成6位數字,2分鐘有效

輸入驗證碼,點擊驗證,返回成功或失敗

每個手機號每天最多只能輸入3次

程式碼:

package com.ztb;

import redis.clients.jedis.Jedis;

import java.util.Random;

public class PhoneCode {
public static void main(String[] args) {
//發送
verifyCode("13525630223");
//驗證
//getRedisCode("13525630223","137663");
}
//驗證碼校驗
public static void getRedisCode(String phone,String code){
//驗證碼key
Jedis jedis = new Jedis("192.168.219.130", 6379);
String codeKey=phone+"code";
String redisCode = jedis.get(codeKey);
//判斷
if(redisCode.equals(code)){
System.out.println("成功");
}else {
System.out.println("失敗");
}
jedis.close();

}
//每個手機每天只能發送三次,驗證碼放到redis中,設置過期時間
public static void verifyCode(String phone){
//連接redis
Jedis jedis = new Jedis("192.168.219.130", 6379);
//拼接key,保證key唯一
//手機發送次數key
String countKey =phone+"count";
//驗證碼key
String codeKey=phone+"code";
//每個手機每天只能發送三次
String count=jedis.get(countKey);

if(count==null){
//沒有發送次數,第一次發送
//設置發送次數為1
jedis.setex(countKey,20*60*60,"1");
}else if(Integer.parseInt(count)<=2){
//發送次數+1
jedis.incr(countKey);
}else if(Integer.parseInt(count)>2){
System.out.println("今天發送次數已經超過三次");
jedis.close();
}
//設置驗證碼到redis中
String code = getCode();
jedis.setex(codeKey,120,code);
jedis.close();


}




//生成6位驗證碼
public static String getCode(){
Random random = new Random();
String code="";
for (int i = 0; i < 6; i++) {
int i1 = random.nextInt(10);
code+=i1;
}
return code;
}
}

7:springboot整合redis:

導入依賴:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="//maven.apache.org/POM/4.0.0" xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //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.6.9</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ztb</groupId>
<artifactId>JedisSpringboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>JedisSpringboot</name>
<description>JedisSpringboot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>

</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes> <include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>

</project>

application.properties:

#redis 配置

#介面
spring.redis.host=192.168.219.130
#介面埠號
spring.redis.port=6379

spring.redis.database=0
#連接池最大連接量
spring.redis.lettuce.pool.max-active=20
#連接最大阻塞時間
spring.redis.lettuce.pool.max-wait=-1
#空閑的最大數量
spring.redis.lettuce.pool.max-idle=5
#空閑的最小數量
spring.redis.lettuce.pool.min-idle=0
#重建連接時間
spring.redis.timeout=1800000

新建config包:package com.ztb.redis.config;

import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
template.setConnectionFactory(factory);
template.setKeySerializer(redisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
}

controller:

測試:

package com.ztb.redis.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;

import javax.annotation.Resource;

@RestController
@RequestMapping("redis")
public class RedisTestController {
@Resource
private RedisTemplate redisTemplate;
@GetMapping("/test")
public String testRedis(){
//設置值到redis
redisTemplate.opsForValue().set("name","luck");
//redis中獲取值
String name =(String) redisTemplate.opsForValue().get("name");
return name;
}

}

啟動並訪問。

package com.ztb.redis.config;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
template.setConnectionFactory(factory);
template.setKeySerializer(redisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
}