4、SpringBoot整合Redis(包含大部分数据类型的操作)

5 篇文章 0 订阅

SpringBoot整合Redis

1、安装Redis,采用离线安装包安装

2、建项目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这一步需要两个依赖,选择web下面的Spring Web和非关系型数据库的Spring Data Redis,然后点击下一步,下一个界面直接点击完成即可。
在这里插入图片描述

3、使用Redis操作

以下是项目结构
在这里插入图片描述

3.1、pom.xml

<?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>
    <groupId>com.zhou</groupId>
    <artifactId>springboot-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-redis</name>
    <description>Demo project for Spring Boot</description>


    <parent>
        <artifactId>springboot-vue</artifactId>
        <groupId>com.zhou</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <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.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>



</project>

3.2、RedisController

package com.zhou.springbootredis.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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("redis")
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    //访问和传值方式:http://127.0.0.1:8080/redis/addName?key=a&value=123456
    //问号后面就是传值
    @GetMapping("addName")
    public String addNmae(@RequestParam String key,@RequestParam String value){
        //设置一个值
        redisTemplate.opsForValue().set(key,value);
        //获取一个值
        return redisTemplate.opsForValue().get(key).toString();
    }
    //访问和传值方式:http://127.0.0.1:8080/redis/addName?key=a&value=123456
    //问号后面就是传值
    @GetMapping("deleteName")
    public String deleteNmae(@RequestParam String key){
        //删除一个值,true成功,false失败
        boolean isSuccess=redisTemplate.delete(key);
        //这里测试的话可以获取一个值,看是否删除成功
        Object obj=redisTemplate.opsForValue().get(key);
        return obj==null?"删除成功":"删除失败";
    }
}

3.3、application.properties

# 应用名称
spring.application.name=springboot-redis
# 应用服务 WEB 访问端口
server.port=8080


# Redis地址
spring.redis.host=192.168.1.204
# Redis端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# Redis数据库索引(默认为0)
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=10
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=10000ms


3.4、RedisConfig

主要解决在redis可视化工具中出现乱码的问题

package com.zhou.springbootredis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 配置连接工厂
        redisTemplate.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        //用这个进行序列化可以在redis可视化工具中查看数据,默认的会有乱码
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        redisTemplate.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jacksonSeial);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}

3.5、测试

首先测试addName方法
在这里插入图片描述
测试deleteName方法
在这里插入图片描述

4、各数据类型的具体操作

4.1、String的操作

set、get、delete直接参照上面
incr、decr,将 key 中储存的数字值增一或减一

incr为每次增加多少,decr为每次减少多少

 @GetMapping("incr")
    public String incr(@RequestParam String key)
    {
        //每次加1
        return redisTemplate.boundValueOps(key).increment(1).toString();
    }
    @GetMapping("decr")
    public String decr(@RequestParam String key)
    {
        //每次减1
        return redisTemplate.boundValueOps(key).decrement(1).toString();
    }
Setex、Setnx,设置过期时间

Redis Setex 命令为指定的 key 设置值及其过期时间。如果 key 已经存在, SETEX 命令将会替换旧的值。
SETNX 是 SET if Not eXists的简写,不存在才设置,否则就不做任何操作
具体实现如下

 /*
    *设置过期时间,如果key存在则覆盖旧值
    * */
    @GetMapping("setex")
    public void setex(@RequestParam String key,@RequestParam String value){
        redisTemplate.opsForValue().set(key,value,20, TimeUnit.SECONDS);
    }
    /*
     *设置过期时间,SETNX 是 SET if Not eXists的简写,不存在才设置,否则就不做任何操作
     * */
    @GetMapping("setnx")
    public void setnx(@RequestParam String key,@RequestParam String value){
        redisTemplate.opsForValue().setIfAbsent(key,value,20, TimeUnit.SECONDS);
    }
ttl,获取过期时间
    /*
    * 获取过期时间
    * */
    public Long ttl(@RequestParam String key){
        return redisTemplate.getExpire("k");
    }

4.2、Hash

hset
/*
    * 命令用于为哈希表中的字段赋值
    * */
    @GetMapping("hset")
    public void hset(){
        redisTemplate.opsForHash().put("myhash","name","张三");
    }
hget
 /*
     * 获取集合中的值
     * */
    @GetMapping("hget")
public void hget(){
        //根据key和字段名获取value
        Object o = redisTemplate.opsForHash().get("myhash", "name");
        //获取所有value
        List list = redisTemplate.opsForHash().values("myhash");
    }
hdel
 /*
     * 删除集合中的值
     * */
    @GetMapping("hdel")
    public void hdel(){
        Long delete = redisTemplate.opsForHash().delete("myhash", "name");
    }
hexists
 /*
     * 判断集合中的值是否存在
     * */
    @GetMapping("hexists")
    public void hexists(){
        Boolean isexists = redisTemplate.opsForHash().hasKey("myhash", "name");
    }

4.3、List

按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边)

rpush
/*
     * 从右边插的示例
     * 从左边插用leftPush
     * */
    @GetMapping("rpush")
    public void rpush(){
        //从右边插
        Long rightPush = redisTemplate.opsForList().rightPush("k", "v");
    }
rpop
 /*
     * 从右边获取示例
     * 从左边用lpop
     * */
    @GetMapping("rpop")
    public void rpop(){
        Object value = redisTemplate.opsForList().rightPop("k");
    }
llen
 /*
     * 命令用于返回列表的长度。 如果列表 key 不存在,则 key 被解释为一个空列表,返回 0 。 如果 key 不是列表类型,返回一个错误
     * */
    @GetMapping("llen")
    public void llen(){
        Long value = redisTemplate.opsForList().size("k");
    }
lrange
 /*
     * Lrange 返回列表中指定区间内的元素
     * 其中 0 表示列表的第一个元素, 1 表示列表的第二个元素,以此类推。 你也可以使用负数下标,以 -1 表示列表的最后一个元素, -2 表示列表的倒数第二个元素,以此类推
     * */
    @GetMapping("lrange")
    public void lrange(){
        List list = redisTemplate.opsForList().range("list", 0, -1);
    }

4.4、Set

sadd
 /*
     * 向集合添加一个或多个成员
     * */
    @GetMapping("sadd")
    public void sadd(){
        //可以添加一个
        Long add = redisTemplate.opsForSet().add("k", "v");
        //可以添加多个
        Long add1 = redisTemplate.opsForSet().add("k", "v1", "v2");
    }
srem
/*
     * 移除集合中的一个或多个成员元素
     * */
    @GetMapping("srem")
    public void srem(){
        Long remove = redisTemplate.opsForSet().remove("k", "v");
        Long remove1 = redisTemplate.opsForSet().remove("k", "v1", "v2");
    }
spop
/*
     * 移除并返回集合中的一个随机元素
     * */
    @GetMapping("spop")
    public void spop(){
        Object value = redisTemplate.opsForSet().pop("k");
    }
scard
/*
     * 获取集合的成员数
     * */
    @GetMapping("scard")
    public void scard(){
        Long size = redisTemplate.opsForSet().size("k");
    }
sinter
 /*
     * 返回给定所有集合的交集
     * */
    @GetMapping("sinter")
    public void sinter(){
        Set intersect = redisTemplate.opsForSet().intersect("k", "k2");
    }
sunion
 /*
     * 返回所有给定集合的并集
     * */
    @GetMapping("sunion")
    public void sunion(){
        Set union = redisTemplate.opsForSet().union("k", "k2");
    }
sdiff
 /*
     * 返回第一个集合与其他集合之间的差异。
     * */
    @GetMapping("sdiff")
    public void sdiff(){
        Set difference = redisTemplate.opsForSet().difference("k", "k2");
    }

4.5、Zset

zadd
 /*
     * 向有序集合添加一个或多个成员,或者更新已存在成员的分数
     * */
    @GetMapping("zadd")
    public void zadd(){
        Boolean add = redisTemplate.opsForZSet().add("k", "aa", 12);
    }
zrevrange
/*
     * 返回有序集中指定区间内的成员,通过索引,分数从高到低
     * */
    @GetMapping("zrevrange")
    public void zrevrange(){
        Set value = redisTemplate.opsForZSet().reverseRange("k", 0, -1);
    }
zrevrangebyscore
 /*
     * 返回有序集中指定分数区间内的成员,分数从高到低排序
     * */
    @GetMapping("zrevrangebyscore")
    public void zrevrangebyscore(){
        Set range = redisTemplate.opsForZSet().reverseRangeByScore("k", 1, 100);
    }
zincrby
 /*
     * 有序集合中对指定成员的分数加上增量 increment
     * */
    @GetMapping("zincrby")
    public void zincrby(){
        Double aDouble = redisTemplate.opsForZSet().incrementScore("k", "aa", 19);
    }
zcard
 /*
     * 获取有序集合的成员数
     * */
    @GetMapping("zcard")
    public void zcard(){
        Long value = redisTemplate.opsForZSet().zCard("k");
    }
zrank
 /*
     * 返回有序集合中指定成员的索引
     * */
    @GetMapping("zrank")
    public void zrank(){
        Long value = redisTemplate.opsForZSet().rank("k", "aa");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值