微服务架构搭建 + 服务启动注册

叁叁肆2018-12-02 14:00

此文已由作者赵计刚薪授权网易云社区发布。

欢迎访问网易云社区,了解更多网易技术产品运营经验。


一、首先编写微服务基础项目framework


1、pom.xml

 View Code

说明:

  • 上边的<packaging>jar</packaging>可以去掉。因为spring-boot-maven-plugin会打jar包的
  • 引入spring-boot-starter-actuator是为了注册服务的时候可以直接使用"http://localhost:8080/health"进行健康检查。见第二十章 springboot + consul
    • 注意:health的port不是固定的8080,而是服务启动的接口,如果服务是以8090启动,使用"http://localhost:8090/health"来检查

2、com.microservice.framework.MySpringAplication

 View Code

注意:这里的main方法声明是要有的(否则无法install为jar)。

3、com.microservice.framework.consul.ConsulRegisterListener

 View Code

注意:这个代码是关键,后边会讲改代码的作用。

其中,ConsulProperties和Consul我们需要在代码中构建成Bean(如下变4和5),之后才能从容器中取出来,否则为null。

4、com.microservice.framework.consul.ConsulProperties

 View Code

注意:

  • 这里使用lombok简化了pojo
  • @value注解中可以指定默认值,查看上边":"后边的值就是

5、com.microservice.framework.consul.ConsulConfig

 View Code

编写完上述代码后,执行"mvn clean install",如果成功的话,此时"framework-1.0-SNAPSHOT.jar"这个jar就会装载到本地的.m2/repository/com/microservice/framework/q.0-SNAPSHOT中了(mac中.m2默认在~下)

 

二、开发第一个微服务myserviceA


像上边所示,我们创建了client和server。

  • server:用于实现具体逻辑
  • client:用于封装server接口(通常就是server模块的controller中的各个url),提供给其他service或gateway甚至是app使用

1、myserviceA

pom.xml

 View Code

2、myserviceA-server

2.1、pom.xml

 View Code

2.2、application.properties

 View Code

说明:

  • service.name(这是一个service在注册中心的唯一标识)
  • service.port
  • service.tag(该值用于在注册中心的配置管理,dev环境下使用dev的配置,prod下使用prod的配置,配置管理通常使用KV来实现的,tag用于构建Key)
  • health.url(健康检查的url)
  • health.interval(每隔10s ping一次health.url,进行健康检查)

2.3、com.microservice.myserviceA.MyServiceAApplication

 View Code

说明:这里调用了framework中的MySpringAplication的run(),该run()首先初始化了SpringApplication实例,之后为该实例添加ConsulRegisterListener实例,最后再执行SpringApplication的run()。

ConsulRegisterListener的执行时机见附4 springboot源码解析-run(),简言之,就是

  • run()方法会先构建容器ApplicationContext,之后将各个BeanDefinition装入该容器,最后刷新容器,这时候执行ConsulRegisterListener中的onApplication方法,用于注册service到consul。

3、myserviceA-client

pom.xml

 View Code

该client以后在需要用到的时候完成。

 

测试:启动consul,开发环境下,直接使用"consul agent -dev"快速启动,查看consul UI,如下:

 

启动"myserviceA-server",启动完成后,查看consul UI,如下:


表示注册成功,我们还可以查看myserviceA的健康检查URL,如下:

 

以上就完成了基本微服务架构的搭建与服务启动时自动注册!