springboot自定义starter

springboot自定义starter,第1张

  • 本章我们介绍如果自定义一个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.examplegroupId>
            <artifactId>factoryStartartifactId>
            <version>0.0.1-SNAPSHOTversion>
        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 "发送成功";
    }


}
  • 目录

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/919312.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存