springboot自定义starter

  • 本章我们介绍如果自定义一个starter

  • 创建springboot 项目

  • 创建factoryAutoConfiguration 自动配置类

package com.example.factorystart.auto;

import com.example.factorystart.bean.FactoryProperties;
import com.example.factorystart.server.Taskfactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@EnableConfigurationProperties(FactoryProperties.class)
public class factoryAutoConfiguration {


    @ConditionalOnMissingBean(Taskfactory.class)
    @Bean
    public Taskfactory getTaskFactory(){
        System.out.printf("加载自动发配置");
        return new Taskfactory();
    }


}



@Component
@ConfigurationProperties("hy.task")
@Data
public class FactoryProperties {

   private   int ThreadCore;
   private int MaxThread;
   private int keepAliveTime;

}

public class Taskfactory {

    class MyFactory implements ThreadFactory {

        @Override
        public Thread newThread(Runnable r) {
            return new Thread();
        }
    }

    private ThreadPoolExecutor executor;
    public Taskfactory(){
        System.out.printf("创建了对象\n");
        executor=new ThreadPoolExecutor(
               properties.getThreadCore(),
                properties.getMaxThread(),
                20,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(properties.getMaxThread()),
                new MyFactory()
        );
    }

    @Autowired
    FactoryProperties properties;

    public void Sumbit(Runnable runnable){
        executor.execute(runnable);
        System.out.printf("你提交了一个任务");
    }
}
  • 创建spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.factorystart.auto.factoryAutoConfiguration
  • 引入该starter
		<dependency>
            <groupId>com.example</groupId>
            <artifactId>factoryStart</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
  • 填写文件

hy.task.MaxCore=100
hy.task.MaxThread=1000
  • 创建个控制器测试

@RestController
@RequestMapping("/Api/Login")
public class LoginController {
    @Autowired
    Taskfactory taskfactory;
   

    @RequestMapping(value = "/SendCode",method ={RequestMethod.GET})
    public String SendCode(@RequestParam String email){
        taskfactory.Sumbit(new Runnable() {
            @Override
            public void run() {
				
            }
        });
        return "发送成功";
    }


}
  • 目录
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值