iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >SpringBoot整合Redis案例分析
  • 753
分享到

SpringBoot整合Redis案例分析

2023-06-19 11:06:18 753人浏览 泡泡鱼
摘要

这篇文章主要介绍了SpringBoot整合Redis案例分析的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇springBoot整合Redis案例分析文章都会有所收获,下面我们一起来看看吧。Springboot整

这篇文章主要介绍了SpringBoot整合Redis案例分析的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇springBoot整合Redis案例分析文章都会有所收获,下面我们一起来看看吧。

Springboot整合Redis

如果没有Redis,就先去下载
  • 下载路径cmd,然后redis-server.exe redis.windows.conf命令既可以启动服

  • 启动服务后,后面的才可以进行整合
  • 在redis目录下点击redis-cli.exe进行测试结果查看,基本操作如下

    • key * :查看存储内容

    • flushdb :清空数据库

如果redis不熟悉去看

undefined

SpringData也是和SpringBoot齐名的项目

说明:在SpringBoot2.x之后,原来使用的jedis被替换为了lettuce

jedis:采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用jedis pool连接池!【类似于Bio:同步阻塞IO】

lettuce:采用Netty【异步请求,性能更高点】,实例可以再多个线程中进行共享,不存在线程不安全的情况!可以减少线程数量了【类似于NIO:同步非阻塞IO】

  • 异步请求一般都需要序列化

源码分析:

@Bean//当这个Bean不存在的时候,这个类就生效//这就说明,我们可以自己定义一个redisTemplate来替换这个默认的!@ConditionalOnMissingBean(name = "redisTemplate")@ConditionalOnSingleCandidate(RedisConnectionFactory.class)public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {        //默认的RedisTemplate没有过多的设置,redis,对象都是需要序列化的!        //两个泛型都是Object类型,我们后面使用需要强制转换:我们需要的类型<String, Object>RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBean//由于String是Redis最常用的类型,所以说单独提出来了一个Bean@ConditionalOnSingleCandidate(RedisConnectionFactory.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}

上手测试【默认的RedisTemplate了解】

1.导入依赖
<!--操作redis-->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency><!--上面redis不兼容时候,可以换成jedis--><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-redis</artifactId>    <exclusions>        <exclusion>            <groupId>io.lettuce</groupId>            <artifactId>lettuce-core</artifactId>        </exclusion>    </exclusions></dependency><dependency>    <groupId>redis.clients</groupId>    <artifactId>jedis</artifactId></dependency>
2.配置连接
# SpringBoot所有的配置类,都有一个自动配置类  RedisAutoConfiguration#  自动配置类都会绑定一个properties配置文件  RedisPropertiesspring:  redis:    host: 127.0.0.1    # Redis服务器连接端口    port: 6379    # Redis数据库索引(默认为0)    database: 0    # Redis服务器连接密码(默认为空)    passWord:    # 连接池最大连接数(使用负值表示没有限制)    pool:      max-active: 200    # 连接池最大阻塞等待时间(使用负值表示没有限制)      max-wait: -1    # 连接池中的最大空闲连接      max-idle: 10    # 连接池中的最小空闲连接      min-idle: 0    # 连接超时时间(毫秒)    timeout: 1000
3.测试
  • 实际开发中我们都不会用这种原生的方式来编写代码

  • 一般我们会将这些常用的操作编写成工具类:redisUtils【后面就会有】
    • 前面还有jdbcUtils和mybatisUtils等

@SpringBootTestclass Redis03SpringbootApplicationTests {    //注入RedisAutoConfiguration里面配置的类    @Autowired    public RedisTemplate redisTemplate;    @Test    void contextLoads() {        //redisTemplate :操作我们的数据库,api和我们的是一样的        //opsForValue   :操作字符串  类似String        //opsForList    :操作List        //除了基本的操作,我们常用的方法都可以直接通过redisTemplate进行操作        //比如事务和基本的CRUD        //获取redis的连接对象,就可以操作数据库的连接了【一般很少来用】        redisTemplate.opsForValue().set("kami", "g1x");        System.out.println(redisTemplate.opsForValue().get("kami"));    }}
4.结果

SpringBoot整合Redis案例分析

问题:写到中文的时候,springboot是正常的,但是从redis中的redis.cli.exe运行keys *会出来乱码

SpringBoot整合Redis案例分析

  • 解决方法:默认的RedisTemplate没有过多的设置,redis,对象都是需要序列化的!
  • 这是默认的序列化配置

SpringBoot整合Redis案例分析

  • 默认序列化方式是jdk序列化

SpringBoot整合Redis案例分析

6.这时候我们就需要自己来写配置类
  • 自己写了后,原来默认的RedisTemplate就会失效

  • 创建一个config

  • @Configurationpublic class RedisConfig {    //编写我们自己的RedisTemplate    @Bean    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {        RedisTemplate<String, Object> template = new RedisTemplate<>();        //这里面到底怎么配置看后面        template.setConnectionFactory(redisConnectionFactory);        return template;    }}

上手测试【自定义的RedisTemplate——实际一般使用】

1.先创建一个pojo,user
//将它变为组件,方便调用@Component@Data@AllArgsConstructor@NoArgsConstructorpublic class User {    private String name;    private Integer age;}
2.测试类写序列化JSON对象操作【这里默认的序列化是JDK序列化】
    @Test    public void test() throws jsonProcessingException {        //真实开发中一般都使用json来传递对象,所以要序列化json        User user = new User("葛", 3);        //所以要序列化成json对象【变成了json字符串】        String jsonUser = new ObjectMapper().writeValueAsString(user);        redisTemplate.opsForValue().set("user", jsonUser);        System.out.println(redisTemplate.opsForValue().get("user"));    }
  • 如果不用上面的序列化json对象操作会报错!String jsonUser = new ObjectMapper().writeValueAsString(user);

  • 下面是关于对象的保存,但是一般都是用json对象

  • SpringBoot整合Redis案例分析

    • 解决方法:在实体类中序列化即可【在企业中,我们所有的pojo都会序列化!SpringBoot】
    • //将它变为组件,方便调用@Component@Data@AllArgsConstructor@NoArgsConstructorpublic class User implements Serializable {    private String name;    private Integer age;}
3.刚才测试的是默认的序列化(JDK),这时候我们自己写其他方式的序列化
  1. 创建一个config

  2. SpringBoot整合Redis案例分析

    //这里面到底怎么配置看后面Jackson2JsonRedisSerializer<Object> objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>();//配置具体的序列化template.seTKEySerializer(objectJackson2JsonRedisSerializer);
    • 多种序列化方式

    1. 写法例子

  3. 自己写很费劲,用已经写好的例子即可

    连接中有不同地方,复制连接中import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;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.StringRedisSerializer; import java.rmi.UnknownHostException; @Configurationpublic class RedisConfig {    @Bean    @SuppressWarnings("all")    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {        // 自定义 String Object        RedisTemplate<String, Object> template = new RedisTemplate();        template.setConnectionFactory(redisConnectionFactory);         // Json 序列化配置        Jackson2JsonRedisSerializer<Object> objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);        // ObjectMapper 转译        ObjectMapper objectMapper = new ObjectMapper();        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);        objectJackson2JsonRedisSerializer.setObjectMapper(objectMapper);         // String 的序列化        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();         // key 采用String的序列化方式        template.setKeySerializer(stringRedisSerializer);        // hash 的key也采用 String 的序列化方式        template.setHashKeySerializer(stringRedisSerializer);        // value 序列化方式采用 jackson        template.setValueSerializer(objectJackson2JsonRedisSerializer);        // hash 的 value 采用 jackson        template.setHashValueSerializer(objectJackson2JsonRedisSerializer);        template.afterPropertiesSet();         return template;    }}
    • 企业中直接拿去使用即可
  4. 编写工具类

    package com.kami.utils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;@Componentpublic final class RedisUtil {    @Autowired    private RedisTemplate<String, Object> redisTemplate;        public boolean expire(String key, long time) {        try {            if (time > 0) {                redisTemplate.expire(key, time, TimeUnit.SECONDS);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public long getExpire(String key) {        return redisTemplate.getExpire(key, TimeUnit.SECONDS);    }        public boolean hashKey(String key) {        try {            return redisTemplate.hasKey(key);        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public void del(String... key) {        if (key != null && key.length > 0) {            redisTemplate.delete(key[0]);        } else {            redisTemplate.delete(CollectionUtils.arrayToList(key));        }    }    //==================================String====================================        public Object get(String key) {        return key == null ? null : redisTemplate.opsForValue().get(key);    }        public boolean set(String key, Object value) {        try {            redisTemplate.opsForValue().set(key, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public boolean set(String key, Object value, long time) {        try {            if (time > 0) {                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);            } else {                set(key, value);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public long incr(String key, long delta) {        if (delta < 0) {            throw new RuntimeException("递增因子必须大于0");        }        return redisTemplate.opsForValue().increment(key, delta);    }        public long decr(String key, long delta) {        if (delta < 0) {            throw new RuntimeException("递减因子必须大于0");        }        return redisTemplate.opsForValue().decrement(key, delta);    }    // ================================Map=================================        public Object hget(String key, String item) {        return redisTemplate.opsForHash().get(key, item);    }        public Map<Object, Object> hmget(String key) {        return redisTemplate.opsForHash().entries(key);    }        public boolean hmset(String key, Map<String, Object> map) {        try {            redisTemplate.opsForHash().putAll(key, map);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public boolean hmset(String key, Map<String, Object> map, long time) {        try {            redisTemplate.opsForHash().putAll(key, map);            if (time > 0) {                expire(key, time);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public boolean hset(String key, String item, Object value) {        try {            redisTemplate.opsForHash().put(key, item, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public boolean hset(String key, String item, Object value, long time) {        try {            redisTemplate.opsForHash().put(key, item, value);            if (time > 0) {                expire(key, time);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public void hdel(String key, Object... item) {        redisTemplate.opsForHash().delete(key, item);    }        public boolean hHasKey(String key, String item) {        return redisTemplate.opsForHash().hasKey(key, item);    }        public double hincr(String key, String item, double by) {        return redisTemplate.opsForHash().increment(key, item, by);    }        public double hdecr(String key, String item, double by) {        return redisTemplate.opsForHash().increment(key, item, -by);    }    // ============================set=============================        public Set<Object> sGet(String key) {        try {            return redisTemplate.opsForSet().members(key);        } catch (Exception e) {            e.printStackTrace();            return null;        }    }        public boolean sHasKey(String key, Object value) {        try {            return redisTemplate.opsForSet().isMember(key, value);        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public long sSet(String key, Object... values) {        try {            return redisTemplate.opsForSet().add(key, values);        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }        public long sSetAndTime(String key, long time, Object... values) {        try {            Long count = redisTemplate.opsForSet().add(key, values);            if (time > 0) {                expire(key, time);            }            return count;        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }        public long sGetSetSize(String key) {        try {            return redisTemplate.opsForSet().size(key);        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }        public long setRemove(String key, Object... values) {        try {            Long count = redisTemplate.opsForSet().remove(key, values);            return count;        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }    // ===============================list=================================        public List<Object> lGet(String key, long start, long end) {        try {            return redisTemplate.opsForList().range(key, start, end);        } catch (Exception e) {            e.printStackTrace();            return null;        }    }        public long lGetListSize(String key) {        try {            return redisTemplate.opsForList().size(key);        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }        public Object lGetIndex(String key, long index) {        try {            return redisTemplate.opsForList().index(key, index);        } catch (Exception e) {            e.printStackTrace();            return null;        }    }        public boolean lSet(String key, Object value) {        try {            redisTemplate.opsForList().rightPush(key, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public boolean lSet(String key, Object value, long time) {        try {            redisTemplate.opsForList().rightPush(key, value);            if (time > 0) {                expire(key, time);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public boolean lSet(String key, List<Object> value) {        try {            redisTemplate.opsForList().rightPushAll(key, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public boolean lSet(String key, List<Object> value, long time) {        try {            redisTemplate.opsForList().rightPushAll(key, value);            if (time > 0) {                expire(key, time);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public boolean lUpdateIndex(String key, long index, Object value) {        try {            redisTemplate.opsForList().set(key, index, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }        public long lRemove(String key, long count, Object value) {        try {            Long remove = redisTemplate.opsForList().remove(key, count, value);            return remove;        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }    // ===============================HyperLogLog=================================    public long pfadd(String key, String value) {        return redisTemplate.opsForHyperLogLog().add(key, value);    }    public long pfcount(String key) {        return redisTemplate.opsForHyperLogLog().size(key);    }    public void pfremove(String key) {        redisTemplate.opsForHyperLogLog().delete(key);    }    public void pfmerge(String key1, String key2) {        redisTemplate.opsForHyperLogLog().union(key1, key2);    }}
    • 我们真实的分发中,或者在你们的公司,一般都可以看到一个公司自己封装RedisUtil

  5. 转到测试类

    @SpringBootTestclass Redis02SpringbootApplicationTests {     @Autowired    // 指定我们自己定义的redis序列化配置    private RedisTemplate<String, Object> redisTemplate;     @Autowired    private RedisUtil redisUtil;    @Test    void test1() {        // 清空数据库        redisTemplate.getConnectionFactory().getConnection().flushDb();         User user = new User("zhangsha", 23);        redisUtil.set("user", user);        System.out.println(redisUtil.get("user"));    }}
    • 这时候注入的RedisTemplate需要导入的是我们的

  6. 结果就是输出前加了转译【不再是乱码】

    1. redis目录中的redis-cle.exe

    2. 执行结果

    3. SpringBoot整合Redis案例分析

关于“SpringBoot整合Redis案例分析”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“SpringBoot整合Redis案例分析”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程网精选频道。

--结束END--

本文标题: SpringBoot整合Redis案例分析

本文链接: https://www.lsjlt.com/news/295845.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringBoot整合Redis案例分析
    这篇文章主要介绍了SpringBoot整合Redis案例分析的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot整合Redis案例分析文章都会有所收获,下面我们一起来看看吧。Springboot整...
    99+
    2023-06-19
  • SpringBoot整合Redis及Redis工具类的实例分析
    SpringBoot整合Redis及Redis工具类的实例分析,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。SpringBoot整合Redis的博客很多,但是很多都不是我想...
    99+
    2023-06-22
  • springBoot整合redis使用案例详解
    一、创建springboot项目(采用骨架方式) 创建完成; 我们分析下pom文件中内容: 所使用到的关键依赖: <!--springBoot集成redis-...
    99+
    2022-11-12
  • springboot整合quartz实例分析
    这篇文章主要讲解了“springboot整合quartz实例分析”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“springboot整合quartz实例分析”吧!一、quartz简介Quart...
    99+
    2023-06-29
  • SpringBoot整合MyBatis的示例分析
    这篇文章主要介绍了SpringBoot整合MyBatis的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。1.整合MyBatis操作前面一篇提到了SpringBoot整...
    99+
    2023-06-15
  • SpringBoot整合MybatisPlus的示例分析
    这篇文章给大家分享的是有关SpringBoot整合MybatisPlus的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。创建个SpringBoot项目勾选生所需的依赖:我把application的后缀改为...
    99+
    2023-06-20
  • springboot与mybatis整合的示例分析
    这篇文章主要介绍了springboot与mybatis整合的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。整合MyBatis新建Spring Boot项目,或以Cha...
    99+
    2023-05-30
    springboot mybatis
  • SpringBoot整合Redis
    SpringBoot中的Redis 在 SpringBoot2.x 之后,原来使用的jedis被替换为了lettuce jedis : 采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用 jedis pool 连接 池! ...
    99+
    2023-09-07
    redis spring boot java
  • springboot整合swagger问题的示例分析
    小编给大家分享一下springboot整合swagger问题的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一.前言解决了一个困扰很久的问题。自己搭建的一...
    99+
    2023-06-14
  • Springboot整合knife4j与shiro的示例分析
    小编给大家分享一下Springboot整合knife4j与shiro的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一、介绍knife4j增强版本的Swa...
    99+
    2023-06-20
  • SpringBoot整合Redis的实现示例
    目录1.需求说明2.整合实现2.1.创建Springboot工程2.2.redis配置3.编写测试类4.注意事项和细节1.需求说明 在 springboot 中 , 整合 redis...
    99+
    2023-01-28
    SpringBoot整合Redis SpringBoot Redis整合
  • SpringBoot整合activemq的案例代码
    目录ActiveMQ是什么1.安装activemq(linux)2.SpringBoot整合activemq案例2.1 pom.xml2.2 application.properti...
    99+
    2022-11-13
  • IDEA SSM整合Redis项目的示例分析
    这篇文章给大家分享的是有关IDEA SSM整合Redis项目的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。IDEA SSM整合Redis项目实例1、pom.xml 配置 <!--&nbs...
    99+
    2023-06-15
  • SpringBoot整合Druid、Redis的示例详解
    目录1.整合Druid1.1Druid简介1.2添加上 Druid 数据源依赖1.3使用Druid 数据源 2.整合redis2.1添加上 redis依赖2.2yml添加r...
    99+
    2022-11-13
  • SpringBoot示例代码整合Redis详解
    目录Redis 简介Redis 优势Redis与其他key-value存储有什么不同添加Redis依赖包配置Redis数据库连接编写Redis操作工具类测试Redis 简介 Redi...
    99+
    2022-11-13
  • SpringBoot整合Redis及Redis工具类撰写实例
    目录一、Maven依赖二、application.properties中加入redis相关配置三、写一个redis配置类四、写一个Redis工具类五、小结SpringBoot整合Re...
    99+
    2022-11-12
  • springboot整合quartz项目使用案例
    目录1. quartz的基础概念2. quartz的简单使用3. quartz与springboot的整合使用4. quartz的持久化5. quartz的misfire策略6、总结...
    99+
    2023-05-20
    springboot整合quartz springboot整合quartz使用
  • Java基础之SpringBoot整合knife4j的示例分析
    这篇文章给大家分享的是有关Java基础之SpringBoot整合knife4j的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。插件的特点非常简洁清爽的UI设计,接口的快速搜索。支持个性化设置,个性化设置包...
    99+
    2023-06-15
  • Springboot整合redis步骤
    一、加入依赖 com.github.spt-oss spring-boot-starter-data-redis 2.0.7.0 redis依赖二、添加redis.properties配置文件 # REDIS...
    99+
    2017-06-25
    Springboot整合redis步骤
  • springboot如何整合Redis
    这篇文章主要介绍springboot如何整合Redis,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!引入依赖:在pom文件中添加redis依赖:<dependency>   ...
    99+
    2023-06-19
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作