我们有很多情况,所以需要不同的启动方式。
1、普通web服务,对外提供接口
2、执行一次的任务,不提供接口
3、dubbo服务,要持续运行,不提供接口
4、cloud微服务,持续运行,但是不比固定端口
普通web服务
启动类
public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
端口
server.port=9000
执行一次的任务
pom修改为:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency>
启动类
@SpringBootApplicationpublic class DemoApplication implements CommandLineRunner {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}@Overridepublic void run(String... args) throws Exception {System.out.println(123);}}
dubbo服务
在刚才的一次性任务基础上,修改run方法。其实就是让它无限sleep而已
@Overridepublic void run(String... args) throws Exception {while (true) {Thread.sleep(Long.MAX_VALUE);}}
eureka-provider
和web服务类似,需要端口,但是对于服务提供方,不需要特定的端口,所以,我们可以给他一个随机端口。
注意:instanceId一定要设置。参考文章
配置端口为0会造成:
- 在注册到Eureka的时候会一个问题:所有实例都使用了同样的实例名(如:Lenovo-zhaiyc:hello-service:0),这导致只出现了一个实例。
- 当使用management.context-path配置了前缀时,默认的statusPageUrl与healthCheckUrl无效。 下面是解决方法:同时配置instance-id和metadata的url
server:port: 0 # 随机端口management:context-path: /manageeureka:instance:instance-id:${spring.application.name}:${random.int}statusPageUrlPath: ${management.context-path}/infohealthCheckUrlPath: ${management.context-path}/health
使用web但不要端口
某些特殊情形需要
public static void main(String[] args) {new SpringApplicationBuilder(DemoApplication.class).web(WebApplicationType.NONE).run(args);}
