SpringBoot入门到精通-SpringBoot自定义starter(六)

本文涉及的产品
云原生内存数据库 Tair,内存型 2GB
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Redis 版,经济版 1GB 1个月
简介: SpringBoot入门到精通-SpringBoot自定义starter

定义自己的starter

1.认识spring-boot-starter

SpringBoot可以很容易就可以整合其他的组件,比如对于SpringMVC而言,我们只需要导入spring-boot-starter-web就可以直接编写Controller。这个包可不仅仅是导入了一个jar,它把集成SpringMVC所需要的所有的jar都导入了进来

在这里插入图片描述

对于不同的组件的集成都有对应的start,比如: spring-boot-starter-redis 就是用来整合Redis,它把Redis所需要的jar都导入进来了。在starter中不仅包含了集成某个组件所需要的所有jar, 还包括集成该组件的配置类。总结如下

  • 它整合了这个模块需要的依赖库;
  • 提供对模块的配置项给使用者;
  • 提供自动配置类对模块内的Bean进行自动装配;

下面我们来开发一个自己的starter

2.定义自己的starter

我们来定义一个自动装配 redis 的 starter,当某个项目导入该starter之后就可以根据默认配置自动去连接redis服务器。如何才能做到这样的效果呢?或许你应该想到了,仿照SpringBoot的自动配置流程,封装一个自己的jar包。那么我们需要做什么事情

  1. 创建一个maven工厂,导入操作redis所需要的jar包,我这里会使用 jedis 来演示
  2. 定义一个Properties类,用来加载yml配置的redis配置项
  3. 新建自动装配类,使用@Configuration和@Bean来进行自动装配
  4. 创建 MET-INF/spring.factories文件,把自动配置类配置进去,让SpringBoot可以自动去加载;

2.1.创建工程,导入依赖

我的项目名为:springboot-starter-redis , 需要导入SpringBoot基础依赖,以及jedis基础依赖。

<packaging>jar</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starters</artifactId>
    <version>2.2.5.RELEASE</version>
</parent>

<dependencies>
    <!-- SpringBoot自动配置基础依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <!-- SpringBoot核心基础依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.2.5.RELEASE</version>
        <scope>compile</scope>
    </dependency>
    <!-- 使用jedis操作Redis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>commons-pool</groupId>
        <artifactId>commons-pool</artifactId>
        <version>1.6</version>
    </dependency>
</dependencies>

2.2.定义Redis自动配置

第一步,先创建一个RedisProperties来,用来读取yaml的配置

//@ConfigurationProperties: 把 "spring.redis" 前缀下的配置同名绑定到该对象的字段上
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
   
   
    //redis主机
    private String host ="127.0.0.1";
    //redis密码
    private String password;
    //redis端口
    private int port = 6379;
    //超时时间,1秒超时
    private int timeout = 1000;
    //最大空闲
    private int maxIdle = 8;
    //最大链接
    private int maxTotal = 8;
    //最大等待超时
    private long maxWaitMillis = -1;
    //开启测试
    private boolean testOnBorrow = false;
    ...省略get,set...
}

第二步:创建Redis自动配置类 , 注册 JedisPool 连接池对象

@Configuration
//如果有Jedis.class这个类就创建Bean
@ConditionalOnClass({
   
   Jedis.class,JedisPoolConfig.class})
//如果还没有创建Jedis,就创建
@ConditionalOnMissingBean(Jedis.class)
//@EnableConfigurationProperties : 启用RedisProperties
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {
   
   

    @Bean
    public JedisPool jedisPool(RedisProperties redisProperties){
   
   
        JedisPoolConfig config = new JedisPoolConfig();
        //最大空闲连接数
        config.setMaxIdle(redisProperties.getMaxIdle());
        //最大链接对象数
        config.setMaxTotal(redisProperties.getMaxTotal());
        //链接超时时间
        config.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
        //获取连接是测试连接是否畅通
        config.setTestOnBorrow(redisProperties.isTestOnBorrow());
        //参数:配置对象,redis主机地址 ,超时时间,密码
        return new JedisPool(config,redisProperties.getHost(),redisProperties.getPort(),redisProperties.getTimeout(),redisProperties.getPassword());
    }

    @Bean
    public RedisTemplate redisTemplate(JedisPool jedisPool){
   
   
        return new RedisTemplate(jedisPool);
    }
}

2.3.创建RedisTemplate

创建RedisTemplate , 该类是是用来操作Redis的工具类,代码如下

public class RedisTemplate {
   
   

    //连接池
    private JedisPool jedisPool;

    public RedisTemplate(JedisPool jedisPool){
   
   
        this.jedisPool = jedisPool;
    }
    public RedisTemplate(){
   
   }


    public Jedis getJedis(){
   
   
        return jedisPool.getResource();
    }
    //保存字符串
    public String set(String key ,String value){
   
   
        Jedis jedis = getJedis();
        String result = jedis.set(key  , value);
        jedis.close();
        return result;
    }
    //获取字符串
    public String get(String key){
   
   
        Jedis jedis = getJedis();
        String result = jedis.get(key);
        jedis.close();
        return result;
    }

}

2.4.创建spring.factories

创建 resources\META-INF\spring.factories 文件,把配置类的名字加进去

org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.whale.config.RedisAutoConfiguration

2.5.打包start

使用terminal,执行 : mvn install ,把工厂打包到本地仓库
在这里插入图片描述

到这里,start开发完毕。接下来就是在项目pom.xml中去引入该start(springboot-starter-redis),当项目启动,SpringBoot自动配置流程会加载 springboot-startr-redis/MATE-INF/spring.factories 中的 RedisAutoConfiguration ,然后其中的JedisPool 和 RedisTemplate都会被注册到Spring容器中。 剩下就是在项目中注入 RedisTemplate 使用接口。

项目结构如下

在这里插入图片描述

3.使用Starter

3.1.pom导入依赖

这里会找到我们上面install的starter项目

<dependency>
    <groupId>cn.whale</groupId>
    <artifactId>springboot-starter-redis</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

3.2.配置Redis

这个配置项目对应了springboot-starter-redis 中的 RedisProperties ,如果不配置会使用默认的值

spring:
  redis:
    password: 123456
    host: 127.0.0.1
    port: 6379

3.3.编写controller

在controller注入 RedisTemplate,进行set,get方法演示

@RestController
public class UserController {
   
   

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/redis/set/{key}/{value}")
    public String redisSet(@PathVariable("key")String key , @PathVariable("value")String value){
   
   
        return redisTemplate.set(key,value);
    }
    @RequestMapping("/redis/get/{key}")
    public String redisGet(@PathVariable("key")String key){
   
   
        return redisTemplate.get(key);
    }

}

3.4.启动测试

启动项目,访问该路径进行测试,效果如下

在这里插入图片描述

测试 get

在这里插入图片描述

下面是Redis中的效果
在这里插入图片描述

你可能会问定义starter有什么用?其实是比较有用的,比如我们要开发一个通用的组件,封装一个jar,这个组件需要被依赖到多个项目中,那么我们怎么样才能在程序启动的时候做一些初始化配置呢?定义starter就是一种很好的方式。

文章结束啦,如果文章对你有所帮助,请一定给个好评哦,请一定给个好评哦,请一定给个好评哦

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
9月前
32SpringBoot自定义Starter
32SpringBoot自定义Starter
46 0
32SpringBoot自定义Starter
|
9月前
|
开发框架 Java Spring
02SpringBoot入门(HelloWorld探究)
02SpringBoot入门(HelloWorld探究)
37 0
|
2月前
|
Java Docker 容器
美团大牛精心整理SpringBoot学习笔记,从Web入门到系统架构
近期慢慢复工,为了准备面试,各路码友们都开始磨拳擦脚,背面试题、知识点。小编最近得一良友赠送了一份关于SpringBoot的学习笔记,简直不要好用,理论解析言简意赅,每一步操作都有图片展示。这么好的东西肯定不能私藏,为了感谢大家在2019年里的支持,我现在将这份笔记赠送给大家,祝大家前程似锦,Offer不断!
|
2月前
|
设计模式 Java 机器人
SpringBoot3自动配置流程 SPI机制 核心注解 自定义starter
SpringBoot3自动配置流程 SPI机制 核心注解 自定义starter
|
17天前
|
IDE Java Maven
SpringBoot自定义starter及自动配置
SpringBoot自定义starter及自动配置
|
21天前
|
Java 关系型数据库 MySQL
Mybatis入门之在基于Springboot的框架下拿到MySQL中数据
Mybatis入门之在基于Springboot的框架下拿到MySQL中数据
18 4
|
21天前
|
Java 应用服务中间件 Maven
Springboot入门基础知识详解 parent starter 引导类 辅助功能
Springboot入门基础知识详解 parent starter 引导类 辅助功能
20 2
|
21天前
|
Java 程序员
浅浅纪念花一个月完成Springboot+Mybatis+Springmvc+Vue2+elementUI的前后端交互入门项目
浅浅纪念花一个月完成Springboot+Mybatis+Springmvc+Vue2+elementUI的前后端交互入门项目
26 1
|
6天前
|
Java Maven 开发者
Spring Boot中的自定义Starter开发
Spring Boot中的自定义Starter开发
|
12天前
|
Java Maven Spring
Spring Boot中的自定义Starter开发
Spring Boot中的自定义Starter开发