首页 > 数据库 >redis的简单使用

redis的简单使用

时间:2022-09-21 22:00:10浏览次数:94  
标签:简单 使用 redis springframework jedis key org import

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="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.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;
}
}

标签:简单,使用,redis,springframework,jedis,key,org,import
From: https://www.cnblogs.com/zhangtaibing/p/16716241.html

相关文章

  • 简单聊聊大A内资的问题
    简单聊聊大A内资的问题转者按:根据对大A的了解,本人同意原文的观点(所以我不碰股票)。至少,按文章说的做,不至于成为冤大头。 简单聊聊内资的问题吧,当然仅代表个人的看法哈,而......
  • 010——面向对象基础案例——简单实现简易购物车代码演示
    熟悉面向对象思维创建类packagecom.google.demo;/***@authorNorth*@date2022/9/2013:27*/publicclassGoods{intid;//编号Stringname;/......
  • KeeWiDB:兼容Redis协议,领跑NoSQL
    如果现在的我们离开了互联网,生活会是什么样子?互联网++++,已经深刻渗透到人们的生活中。不知道大家有没有想过?每一个互联网+结合的背后都是海量的存储需求。你查看的每一个......
  • WSL+Redis
    WSL+Redis最近恶补Spring*心有余而力不足,打算补充一些与自身技术栈耦合度小(相比来说)的知识,选择了Redis。Redis官方建议配置到Linux操作系统中,直接部署到云服务器,有被黑的......
  • skywalking安装以及使用go
    Skywalking是分布式系统的应用程序性能监视工具,专为微服务、云原生架构和基于容器(Docker、K8s)架构而设计。提供分布式追踪、服务网格遥测分析、度量聚合和可视化一体化解决......
  • Phoenix使用及搭建 bulkLoad实现批量导入
    PhoenixPhoenix和hbase共用一个zookeeper,但是在刚建好Phoenix的时候是读不到hbase中的表的,在Phoenix中建过表之后在hbase中可以看到,在hbase中建过表Phoenix中看不到Hbas......
  • 如何使用 Git 管理配置文件
    现在很多软件的配置都可以在线同步或者支持导入导出,可以很方便的在不同设备上使用。但电脑上还有很多本地配置文件没有办法同步,夸多个设备使用时很难保持一致,换电脑也很麻......
  • Vue 状态管理 Pinia 在UNI-APP下使用说明
    状态管理Pinia此功能和VUEX类似,局有全站通用状态共享的特性。在 HBuilderX下不需要安装,直接使用即可,步骤如下:第一步:在main.js中引入插件:import{createSSRApp......
  • 缓冲流的使用
    缓冲流的使用一,缓冲流的使用1.缓冲流BufferedInputStream字节BufferedOutputStreamBufferedReader字符BufferedWriter2.作用提供流的读取,写入的速度提高读写速......
  • vue 中使用 eslint 常见的 4 个报错小结
    前言eslint是什么?一个用来识别javascript语法规则和代码风格的检查工具,以避免一些如拼写或语法错误等低级错误的发生,并统一代码风格但在实际开发中,可能总是遇到一......