【SpringBoot】SpringBoot整合Redis(Lettuce)

Jedis和Lettuce的区别

  • Lettuce 和 Jedis 的都是连接Redis Server的客户端
  • Jedis是直接连接Redis Server,在多线程环境下是非线程安全的,只有使用连接池
  • Lettuce是基于Netty实现,是线程安全的
  • 在SpringBoot 1.5.x版本默认的Redis客户端是Jedis实现的,SpringBoot 2.x版本默认客户端是用lettuce实现的

以下步骤为SpringBoot整合Lettuce版的Redis

1、导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.3.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.9.0</version>
</dependency>

2、配置application.yml

  • 创建SpringBoot工程默认是application.propertis,但推荐使用.yml文件,所以我将其修改为.yml文件

  • SpringBoot默认会加载application.propertis或者application.yml,两种都可识别

spring:
  redis:
    database: 0
    host: 192.168.229.11
    port: 6379
    password: 123456 # 如果没有密码,可以不写
    lettuce:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0
    timeout: 2000

3、编写配置类

  • 因为默认的模板只能存储字符串类型的,所以我们需要自定义RedisTemplate,满足可以存放更多类型的数据
@Configuration
public class LettuceRedisConfig {

    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }

}

4、创建工具类

@Component
public class RedisUtils {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 设置key-value
     * @param key 键
     * @param value 值
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置带生存时间的key-value
     * @param key 键
     * @param value 值
     * @param timeout 生存时间
     * @param unit 时间单位
     */
    public void set(String key, String value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }
    
    /**
     * 设置指定数据的生存时间。
     *
     * @param key 键
     * @param time 生存时间(秒)
     */
    public void expire(String key, long time) {
        redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }
    
    /**
     * 根据key,获取值
     * @param key 键
     * @return 获取到的值
     */
    public String get(String key) {
        return String.valueOf(redisTemplate.opsForValue().get(key));
    }

    /**
     * 删除指定信息。
     *
     * @param key 键
     * @return 是否删除成功
     */
    public boolean delete(String key) {
        return redisTemplate.delete(key);
    }
}

5、使用

// 在需要的类中引用
@Resource
private RedisUtils redisUtils;


// 然后在需要的地方使用
redisUtils.set(phone, phoneCode, 60, TimeUnit.SECONDS);

执行之后,可以通过Redis的图形化工具(Redis Desktop Manager)查询添加的结果

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
# Geek-Framework 微服务快速开发脚手架 ### 平台简介 Geek-Framework是基于多个优秀的开源项目,高度整合封装而成的高效,高性能,强安全性的**开源**Java微服务快速开发框架。 Geek-Framework是在SpringBoot基础上搭建的一个Java基础开发框架,以Spring MVC为模型视图控制器,MyBatis为数据访问层, Apache Shiro和Spring-Security为权限授权层,redis进行缓存。 Geek-Framework主要定位于微应用的开发,已内置后台系统的基础功能,用户管理、角色管理、权限管理、会员管理、日志管理等;前台已经实现用户登录,注册等基础功能。 同时前后台会员实现分表管理,可扩展多角色系统、多权限系统。 采用分层设计、双重验证、提交数据安全编码、密码加密、访问验证、数据权限验证。 使用Maven做项目管理,提高项目的易开发性、扩展性。 --- ###更新日期2019-01-16 * 升级springboot版本为2.1.2.RELEASE application.yml增加以下配置,兼容最新的springboot版本 > spring:main:allow-bean-definition-overriding: true * 移除j2cache支持,移除原因为简化新手用户部署系统配置 * 更改后台登录为单realm,不再支持多realm * 优化日期时间工具类,使用Instant、LocalDateTime、LocalDate实现线性安全 * 修复Java开发规约中级警告及部分低级警告 * 增加debug日志输出开关 ###更新日期2018-12-28 * 项目增加健康检查暴露配置 * 根据JAVA开发手册对项目部分不符合开发手册的代码进行了修正,已修复高级警告、中级警告,由于低级警告较多,尚未修复,后续将持续修复 * 给前期已经使用项目的同学,可以使用【阿里巴巴Java开发规约插件p3c】进行修正,造成不便深表歉意 ###更新日期2018-10-08 * 最近学习了远程过程调用协议RPC(Remote Procedure Call Protocol),将本框架与dubbo做了一个集成,详见dubbo分支, * 为了方便大学家习dubbo的运行机制,本框架将dubbo的provider和customer作了一个整合,将官方demo里的方多应用整合成了一个,即在同一应用内启动消费端和服务端 * 注:如有实际业务需要请将服务端与消费端分离,此处整合仅供学习dubbo的运行机制和思想 ###更新日期2018-09-19 * 升级mybatis包为mybatis-spring-boot-starter,移除原有mybatis包 * 升级mapper包为mapper-spring-boot-starter * 升级pagehelper包为pagehelper-spring-boot-starter增加pagehelper-spring-boot-autoconfigure包 * 更改mybatis、mapper和pagehelper为自动配置,配置方式详见application.yml * 移除MyBatisConfig.java和MybatisMapperScannerConfig.java文件 * 更改升级pagehelper之后对排序方式的处理方式 * 增加事务测试样例,详见AdminController的save方法,此坑很深,爬了一天,由于没有对spring事务的深入了解,导致事务一直不成功,原因在于spring事务只能处理没有被捕获的异常信息,如果对方法增加了事务,请尽量避免用catch来获取异常,或进在cache里面增加抛出异常功能,使事务能够访问到 ###更新日期2018-09-19 * 升级J2cache为2.7.0版本,主要修复channel获取次数过多导致的错误问题,另个j2cache后期可能会移除对jedis的支持,所以还是提前升级了吧 * 调整二级缓存redislettucelettucespring推荐的redis操作方式,另个 ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。
本项目示例基于spring boot 最新版本(2.1.9)实现,Spring BootSpring Cloud 学习示例,将持续更新…… 在基于Spring BootSpring Cloud 分布微服务开发过程中,根据实际项目环境,需要选择、集成符合项目需求的各种组件和积累各种解决方案。基于这样的背景下,我开源了本示例项目,方便大家快速上手Spring BootSpring Cloud 。 每个示例都带有详细的介绍文档、作者在使用过程中踩过的坑、解决方案及参考资料,方便快速上手为你提供学习捷径,少绕弯路,提高开发效率。 有需要写关于spring bootspring cloud示例,可以给我提issue哦 ## 项目介绍 spring boot demo 是一个Spring BootSpring Cloud的项目示例,根据市场主流的后端技术,共集成了30+个demo,未来将持续更新。该项目包含helloworld(快速入门)、web(ssh项目快速搭建)、aop(切面编程)、data-redis(redis缓存)、quartz(集群任务实现)、shiro(权限管理)、oauth2(四种认证模式)、shign(接口参数防篡改重放)、encoder(用户密码设计)、actuator(服务监控)、cloud-config(配置中心)、cloud-gateway(服务网关)、email(邮件发送)、cloud-alibaba(微服务全家桶)等模块 ### 开发环境 - JDK1.8 + - Maven 3.5 + - IntelliJ IDEA ULTIMATE 2019.1 - MySql 5.7 + ### Spring Boot 模块 模块名称|主要内容 ---|--- helloworld|[spring mvc,Spring Boot项目创建,单元测试](https://github.com/smltq/spring-boot-demo/blob/master/helloworld/HELP.md) web|[ssh项目,spring mvc,过滤器,拦截器,监视器,thymeleaf,lombok,jquery,bootstrap,mysql](https://github.com/smltq/spring-boot-demo/blob/master/web/HELP.md) aop|[aop,正则,前置通知,后置通知,环绕通知](https://github.com/smltq/spring-boot-demo/blob/master/aop/HELP.md) data-redis|[lettuce,redis,session redis,YAML配置,连接池,对象存储](https://github.com/smltq/spring-boot-demo/blob/master/data-redis/HELP.md) quartz|[Spring Scheduler,Quartz,分布式调度,集群,mysql持久化等](https://github.com/smltq/spring-boot-demo/blob/master/quartz/HELP.md) shiro|[授权、认证、加解密、统一异常处理](https://github.com/smltq/spring-boot-demo/blob/master/shiro/HELP.md) sign|[防篡改、防重放、文档自动生成](https://github.com/smltq/spring-boot-demo/blob/master/sign/HELP.md) security|[授权、认证、加解密、mybatis plus使用](https://github.com/smltq/spring-boot-demo/blob/master/security/HELP.md) mybatis-plus-generator|[基于mybatisplus代码自动生成](https://github.com/smltq/spring-boot-demo/blob/master/mybatis-plus-generator) mybatis-plus-crud|[基于mybatisplus实现数据库增、册、改、查](https://github.com/smltq/spring-boot-demo/blob/master/mybatis-plus-crud) encoder|[主流加密算法介绍、用户加密算法推荐](https://github.com/smltq/spring-boot-demo/blob/master/encoder/HELP.md) actuator|[autuator介绍](https://github.com/smltq/spring-boot-demo/blob/master/actuator/README.md) admin|[可视化服务监控、使用](https://github.com/smltq/spring-boot-demo/blob/master/admin/README.md) security-oauth2-credentials|[oauth2实现密码模式、客户端模式](https://github.com/smltq/spring-boot-demo/blob/master/security-oauth2-credentials/README.md) security-oauth2-auth-code|[基于spring boot实现oauth2授权模式](https://github.com/smltq/spring-boot-demo/blob/master/security-oauth2-auth-code/README.md) mybatis-multi-datasource|[mybatis、数据库集群、读写分离、读库负载均衡](https://github.com/smltq/spring-boot-demo/blob/master/mybatis-multi-datasource) template-thymeleaf|[thymeleaf实现应用国际化示例](https://github.com/smltq/spring-boot-demo/blob/master/template-thymeleaf) mq-redis|[redis之mq实现,发布订阅模式](https://github.com/smltq/spring-boot-demo/blob/master/mq-redis) email|[email实现邮件发送](https://github.com/smltq/spring-boot-demo/blob/master/email) jGit|[java调用git命令、jgit使用等](https://github.com/smltq/spring-boot-demo/blob/master/jGit) webmagic|[webmagic实现某电影网站爬虫示例](https://github.com/smltq/spring-boot-demo/blob/master/webmagic) netty|[基于BIO、NIO等tcp服务器搭建介绍](https://github.com/smltq/spring-boot-demo/blob/master/netty) ### Spring Cloud 模块 模块名称|主要内容 ---|--- cloud-oauth2-auth-code|[基于spring cloud实现oath2授权模式](https://github.com/smltq/spring-boot-demo/blob/master/cloud-oauth2-auth-code) cloud-gateway|[API主流网关、gateway快速上手](https://github.com/smltq/spring-boot-demo/blob/master/cloud-gateway) cloud-config|[配置中心(服务端、客户端)示例](https://github.com/smltq/spring-boot-demo/blob/master/cloud-config) cloud-feign|[Eureka服务注册中心、负载均衡、声明式服务调用](https://github.com/smltq/spring-boot-demo/blob/master/cloud-feign) cloud-hystrix|[Hystrix服务容错、异常处理、注册中心示例](https://github.com/smltq/spring-boot-demo/blob/master/cloud-hystrix) cloud-zuul|[zuul服务网关、过滤器、路由转发、服务降级、负载均衡](https://github.com/smltq/spring-boot-demo/blob/master/cloud-zuul) cloud-alibaba|[nacos服务中心、配置中心、限流等使用(系列示例整理中...)](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba) #### Spring Cloud Alibaba 模块 模块名称|主要内容 ---|--- nacos|[Spring Cloud Alibaba(一)如何使用nacos服务注册和发现](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README1.md) config|[Spring Cloud Alibaba(二)配置中心多项目、多配置文件、分目录实现](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README2.md) Sentinel|[Spring Cloud Alibaba(三)Sentinel之熔断降级](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README3.md) Dubbo|[Spring Cloud Alibaba(四)Spring Cloud与Dubbo的融合](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README4.md) RocketMQ|[Spring Cloud Alibaba(五)RocketMQ 异步通信实现](https://github.com/smltq/spring-boot-demo/blob/master/cloud-alibaba/README5.md) ### 其它 模块名称|主要内容 ---|--- leetcode|[力扣题解目录](https://github.com/smltq/spring-boot-demo/blob/master/leetcode) ## Spring Boot 概述 Spring Boot简化了基于Spring的应用开发,通过少量的代码就能创建一个独立的、产品级别的Spring应用。 Spring BootSpring平台及第三方库提供开箱即用的设置,这样你就可以有条不紊地开始。多数Spring Boot应用只需要很少的Spring配置。 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Sprin
Spring Boot中,可以通过配置文件或编程方式来设置Redis线程池。以下是通过编程方式实现整合Redis并设置Redis线程池的步骤: 1. 首先,在你的Spring Boot项目中,添加对RedisLettuceRedisJava客户端)的依赖。可以在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </dependency> ``` 2. 在application.properties或application.yml配置文件中添加Redis相关配置,包括主机名、端口号、密码等。例如: ```yaml spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 3. 创建Redis连接工厂类,可以使用LettuceConnectionFactory。在该类中,你可以设置与Redis连接相关的属性,包括连接池配置。下面是一个示例: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; @Configuration public class RedisConfig { @Value("${spring.redis.host}") private String redisHost; @Value("${spring.redis.port}") private int redisPort; @Value("${spring.redis.password}") private String redisPassword; @Bean public LettuceConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort); config.setPassword(redisPassword); return new LettuceConnectionFactory(config); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory()); return redisTemplate; } } ``` 在上述示例中,LettuceConnectionFactory被创建为一个Bean,并通过RedisStandaloneConfiguration设置了连接的主机名、端口号和密码。然后,将该连接工厂设置到RedisTemplate中。 4. 在需要使用Redis的地方,注入RedisTemplate,并调用其相关方法来操作Redis。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class MyService { private final RedisTemplate<String, Object> redisTemplate; @Autowired public MyService(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } public void saveData(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object getData(String key) { return redisTemplate.opsForValue().get(key); } } ``` 上述示例中的MyService类注入了RedisTemplate,并通过redisTemplate实现了保存数据和获取数据的方法。 这样,你就可以使用Spring Boot整合Redis并设置Redis线程池了。注意,在实际应用中,你可能还需要做一些其他配置和异常处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值