Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中涉及的配置管理、服务发现、断路器、智能路由、微代理、控制总线、全局锁、决策竞选、分布式会话和集群状态管理等操作提供了一种简单的开发方式。
Spring Cloud包含了多个子项目(针对分布式系统中涉及的多个不同开源产品),比如:Spring Cloud Config、Spring Cloud Netflix、Spring Cloud CloudFoundry、Spring Cloud AWS、Spring Cloud Security、Spring Cloud Commons、Spring Cloud Zookeeper、Spring Cloud CLI等项目。
微服务架构“微服务架构”在这几年非常的火热,以至于关于微服务架构相关的开源产品被反复的提及(比如: netflix、dubbo),Spring Cloud也因Spring社区的强大知名度和影响力也被广大架构师与开发者备受关注。
那么什么是“微服务架构”呢?简单的说,微服务架构就是将一个完整的应用从数据存储开始垂直拆分成多个不同的服务,每个服务都能独立部署、独立维护、独立扩展,服务与服务间通过诸如RESTful API的方式互相调用。
对于“微服务架构”,大家在互联网可以搜索到很多相关的介绍和研究文章来进行学习和了解。也可以阅读始祖Martin Fowler的《Microservices》(中文版翻译点击查看),本文不做更多的介绍和描述。
服务治理在简单介绍了Spring Cloud和微服务架构之后,下面回归本文的主旨内容,如何使用Spring Cloud来实现服务治理。
由于Spring Cloud为服务治理做了一层抽象接口,所以在Spring Cloud应用中可以支持多种不同的服务治理框架,比如:Netflix Eureka、Consul、Zookeeper。在Spring Cloud服务治理抽象层的作用下,我们可以无缝地切换服务治理实现,并且不影响任何其他的服务注册、服务发现、服务调用等逻辑。
所以,下面我们通过Eureka这种种服务治理的实现来体会Spring Cloud这一层抽象所带来的好处。
下一篇介绍基于Consul的服务注册与调用。
首先,我们来尝试使用Spring Cloud Eureka来实现服务治理。
Consul是一套开源的分布式服务发现和配置管理系统,由 HashiCorp 公司用Go 语言开发。
它具有很多优点。包括: 基于 raft协议,比较简洁; 支持健康检查, 同时支持 HTTP 和 DNS 协议 支持跨数据中心的WAN 集群 提供图形界面 跨平台,支持 Linux、Mac、Windows
下面,就来具体看看如何使用Spring Cloud Consul实现服务治理,这里使用Consul为服务注册中心工程、consul-provider服务提供者工程、consul-consumer服务消费者工程。
准备工作环境:
windows jdk 8 maven 3.0 IDEA构建工程
首先构建父工程,引入父工程依赖:
4.0.0 cn.zhangbox spring-cloud-study1.0-SNAPSHOT cn.zhangbox spring-cloud-consulpom 1.0-SNAPSHOT consul-provider consul-consumer
父工程取名为:spring-cloud-consul
构建子工程,分别创建工程名为:、consul-provider、consul-consumer并在pom中加入以下依赖:
4.0.0 cn.zhangbox spring-cloud-consul1.0-SNAPSHOT cn.zhangbox consul-provider0.0.1-SNAPSHOT jar consul-provider this project for Spring Boot UTF-8 UTF-8 1.8 3.4 1.10 1.2.0 1.16.14 1.2.41 1.1.2 aliyunmaven http://maven.aliyun.com/nexus/content/groups/public/ org.mybatis.spring.boot mybatis-spring-boot-starter${mybatis-spring-boot.version} org.springframework.cloud spring-cloud-starter-consul-discoveryorg.springframework.boot spring-boot-starter-actuatororg.springframework.boot spring-boot-starter-webio.springfox springfox-swagger22.6.1 io.springfox springfox-swagger-ui2.6.1 mysql mysql-connector-javaruntime org.springframework.boot spring-boot-starter-testtest org.apache.commons commons-lang3${commons-lang3.version} commons-codec commons-codec${commons-codec.version} com.alibaba fastjson${fastjson.version} com.alibaba druid-spring-boot-starter${druid.version} org.projectlombok lombok${lombok.version} org.springframework.cloud spring-cloud-dependenciesDalston.SR1 pom import eureka-provider org.springframework.boot spring-boot-maven-plugin
4.0.0 cn.zhangbox spring-cloud-eureka1.0-SNAPSHOT cn.zhangbox eureka-provider0.0.1-SNAPSHOT jar eureka-provider this project for Spring Boot UTF-8 UTF-8 1.8 3.4 1.10 1.2.0 1.16.14 1.2.41 1.1.2 aliyunmaven http://maven.aliyun.com/nexus/content/groups/public/ org.mybatis.spring.boot mybatis-spring-boot-starter${mybatis-spring-boot.version} org.springframework.cloud spring-cloud-starter-eurekaorg.springframework.boot spring-boot-starter-webio.springfox springfox-swagger22.6.1 io.springfox springfox-swagger-ui2.6.1 mysql mysql-connector-javaruntime org.springframework.boot spring-boot-starter-testtest org.apache.commons commons-lang3${commons-lang3.version} commons-codec commons-codec${commons-codec.version} com.alibaba fastjson${fastjson.version} com.alibaba druid-spring-boot-starter${druid.version} org.projectlombok lombok${lombok.version} org.springframework.cloud spring-cloud-dependenciesDalston.SR1 pom import eureka-provider org.springframework.boot spring-boot-maven-plugin
4.0.0 cn.zhangbox spring-cloud-consul1.0-SNAPSHOT cn.zhangbox consul-consumer0.0.1-SNAPSHOT jar consul-consumer this project for Spring Boot UTF-8 UTF-8 1.8 3.4 1.10 1.2.0 1.16.14 1.2.41 1.1.2 aliyunmaven http://maven.aliyun.com/nexus/content/groups/public/ org.springframework.cloud spring-cloud-starter-consul-discoveryorg.springframework.boot spring-boot-starter-actuatororg.springframework.cloud spring-cloud-starter-feignorg.springframework.boot spring-boot-starter-webio.springfox springfox-swagger22.6.1 io.springfox springfox-swagger-ui2.6.1 org.springframework.boot spring-boot-starter-testtest org.apache.commons commons-lang3${commons-lang3.version} commons-codec commons-codec${commons-codec.version} com.alibaba fastjson${fastjson.version} org.projectlombok lombok${lombok.version} org.springframework.cloud spring-cloud-dependenciesDalston.SR1 pom import eureka-provider org.springframework.boot spring-boot-maven-plugin
工程构建完成。
服务注册中心搭建Window下安装:
window下安装Consul
Linux下安装:
CentOS 安装 Consul 服务注册和发现软件
Consul安装 linux环境
至此consul注册中心创建完成,window下本机安装的consul浏览器输入地址:http://localhost:8500
linux下安装的只需要把localhost换成对应的ip即可
可以看到如下页面,表示服务启动OK
这里这看到还没有服务暴露出来,是因为还没创建服务提供者工程。
这里服务提供者是使用之前SpringBoot进阶教程 | 第三篇:整合Druid连接池以及Druid监控改造而来,这里一样的部分就不再重复说明,下面将说明新增的部分。
首先:修改application.yml配置为如下:
#公共配置
server:
port: 80
tomcat:
uri-encoding: UTF-8
spring:
application:
name: consul-provider
#激活哪一个环境的配置文件
profiles:
active: dev
#连接池配置
datasource:
driver-class-name: com.mysql.jdbc.Driver
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 配置测试查询语句
validationQuery: SELECt 1 FROM DUAL
# 初始化大小,最小,最大
initialSize: 10
minIdle: 10
maxActive: 200
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 180000
testOnBorrow: false
testWhileIdle: true
removeAbandoned: true
removeAbandonedTimeout: 1800
logAbandoned: true
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxOpenPreparedStatements: 100
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#配置consul获取服务地址,这里使用的是本地提供的注册中心
cloud:
consul:
#consul服务地址
host: localhost
#consul端口号
port: 8500
discovery:
#配置注册中心显示当前服务的ip
prefer-ip-address: true
#配置当前服务的ip和端口号
#instance-id: ${spring.cloud.client.ipAddress}:${server.port}
#配置该项点击ip会跳转至对应的接口swagger页面
health-check-url: http://${spring.cloud.client.ipAddress}:${server.port}/swagger-ui.html # ${server.port}为该服务的端口号
#mybatis
mybatis:
# 实体类扫描
type-aliases-package: cn.zhangbox.springboot.entity
# 配置映射文件位置
mapper-locations: classpath:mapperfavicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-09 11:14:58.382 WARN 2772 --- [ main] o.s.c.n.a.ArchaiusAutoConfiguration : No spring.application.name found, defaulting to 'application'
2018-08-09 11:14:58.386 WARN 2772 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2018-08-09 11:14:58.387 INFO 2772 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-08-09 11:14:58.399 WARN 2772 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2018-08-09 11:14:58.399 INFO 2772 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-08-09 11:15:01.812 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-08-09 11:15:01.814 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'statFilter' has been autodetected for JMX exposure
2018-08-09 11:15:01.814 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-08-09 11:15:01.827 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'configurationPropertiesRebinder' has been autodetected for JMX exposure
2018-08-09 11:15:01.828 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'refreshEndpoint' has been autodetected for JMX exposure
2018-08-09 11:15:01.828 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'restartEndpoint' has been autodetected for JMX exposure
2018-08-09 11:15:01.829 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'environmentManager' has been autodetected for JMX exposure
2018-08-09 11:15:01.830 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'serviceRegistryEndpoint' has been autodetected for JMX exposure
2018-08-09 11:15:01.831 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'refreshScope' has been autodetected for JMX exposure
2018-08-09 11:15:01.834 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'environmentManager': registering with JMX server as MBean [org.springframework.cloud.context.environment:name=environmentManager,type=EnvironmentManager]
2018-08-09 11:15:02.698 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'restartEndpoint': registering with JMX server as MBean [org.springframework.cloud.context.restart:name=restartEndpoint,type=RestartEndpoint]
2018-08-09 11:15:02.715 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'serviceRegistryEndpoint': registering with JMX server as MBean [org.springframework.cloud.client.serviceregistry.endpoint:name=serviceRegistryEndpoint,type=ServiceRegistryEndpoint]
2018-08-09 11:15:02.725 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'refreshScope': registering with JMX server as MBean [org.springframework.cloud.context.scope.refresh:name=refreshScope,type=RefreshScope]
2018-08-09 11:15:02.742 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'configurationPropertiesRebinder': registering with JMX server as MBean [org.springframework.cloud.context.properties:name=configurationPropertiesRebinder,context=60222fd8,type=ConfigurationPropertiesRebinder]
2018-08-09 11:15:02.747 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.alibaba.druid.spring.boot.autoconfigure:name=dataSource,type=DruidDataSourceWrapper]
2018-08-09 11:15:02.750 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'refreshEndpoint': registering with JMX server as MBean [org.springframework.cloud.endpoint:name=refreshEndpoint,type=RefreshEndpoint]
2018-08-09 11:15:02.754 INFO 2772 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'statFilter': registering with JMX server as MBean [com.alibaba.druid.filter.stat:name=statFilter,type=StatFilter]
2018-08-09 11:15:03.294 INFO 2772 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2018-08-09 11:15:03.402 INFO 2772 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2018-08-09 11:15:03.403 INFO 2772 --- [ main] d.s.w.p.documentationPluginsBootstrapper : Context refreshed
2018-08-09 11:15:03.498 INFO 2772 --- [ main] d.s.w.p.documentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2018-08-09 11:15:03.551 INFO 2772 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
2018-08-09 11:15:03.982 WARN 2772 --- [ main] s.d.s.w.r.p.ParameterDataTypeReader : Trying to infer dataType org.springframework.ui.ModelMap
2018-08-09 11:15:04.093 INFO 2772 --- [ main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2018-08-09 11:15:04.768 INFO 2772 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-08-09 11:15:04.777 INFO 2772 --- [ main] o.s.c.c.s.ConsulServiceRegistry : Registering service with consul: NewService{id='application', name='application', tags=[], address='windows10.microdone.cn', port=8080, enableTagOverride=null, check=Check{script='null', interval=10s, ttl=null, http=http://windows10.microdone.cn:8080/health, tcp=null, timeout=null, deregisterCriticalServiceAfter=null, tlsSkipVerify=null}, checks=null}
2018-08-09 11:15:04.926 INFO 2772 --- [ main] c.z.c.p.ConsulProviderApplication : Started ConsulProviderApplication in 27.167 seconds (JVM running for 31.23)
2018-08-09 11:15:05.338 INFO 2772 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]: Initializing Spring frameworkServlet 'dispatcherServlet'
2018-08-09 11:15:05.338 INFO 2772 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : frameworkServlet 'dispatcherServlet': initialization started
2018-08-09 11:15:05.379 INFO 2772 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : frameworkServlet 'dispatcherServlet': initialization completed in 41 ms
至此consul-provider服务提供者创建完成,浏览器输入地址:http://localhost:8500/
可以看到如下页面,表示服务注册OK
浏览器输入地址:http://localhost:8080/swagger-ui.html后可以跳转看到`swagger`的页面并可是测试服务提供者的接口,如下:
这里构建的工程名为consul-consumer,上文已经构建了工程但是没有创建目录,这里只需要在java目录下创建config、controller,service,包即可,这里服务的消费是通过feign来进行服务调用的,后面会有专门以篇文章来讲feign。
首先:在consul-consumer工程下resource目录下添加application.yml文件并加入以下配置:
#公共配置
server:
port: 80
tomcat:
uri-encoding: UTF-8
spring:
#服务名称,更关键,使用feign进行服务消费将以此为依据
application:
name: consul-consumer
#激活哪一个环境的配置文件
profiles:
active: dev
#配置consul获取服务地址,这里使用的是本地提供的注册中心
cloud:
consul:
#consul服务地址
host: localhost
#consul端口号
port: 8500
discovery:
#配置注册中心显示当前服务的ip
prefer-ip-address: true
#配置当前服务的ip和端口号
#instance-id: ${spring.cloud.client.ipAddress}:${server.port}
#配置该项点击ip会跳转至对应的接口swagger页面
health-check-url: http://${spring.cloud.client.ipAddress}:${server.port}/swagger-ui.html # ${server.port}为该服务的端口号
---
#开发环境配置
server:
#端口
port: 8081
spring:
profiles: dev
#日志
logging:
config: classpath:log/logback.xml
path: log/consul-consumer
---
#测试环境配置
server:
#端口
port: 8082
spring:
profiles: test
#日志
logging:
config: classpath:log/logback.xml
path: /home/log/consul-consumer
---
#生产环境配置
server:
#端口
port: 8083
spring:
profiles: prod
#日志
logging:
config: classpath:log/logback.xml
path: /home/log/consul-consumer
其次:在config目录下增加SwaggerConfig类加入以下代码:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket userApi() {
Docket docket = new Docket(documentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.zhangbox.eureka.consumer.controller"))//过滤的接口,有这扫描才会看到接口信息
.paths(PathSelectors.any())
.build();
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("eureka服务端消费者接口平台").description("服务相关数据接口")
.termsOfServiceUrl("http://www.zhang.box.cn/").contact("技术开发部")
.license("Licence Version 1.0").licenseUrl("#").version("1.0").build();
}
}
接着:在service包下创建StudentConsumerService类并加入以下代码:
@FeignClient(value = "consul-provider")
public interface StudentConsumerService {
@RequestMapping(value = "/student/list",method = RequestMethod.GET)
String getStudentList(@RequestParam(value = "sname") String sname, @RequestParam(value = "age") Integer age);
}
然后:在controller包下创建StudentConteroller并加入如下代码:
@Controller
@RequestMapping("/student")
@Api(value = "eureka-consumer", description = "学生查询接口")
public class StudentConteroller {
private static final Logger LOGGER = LoggerFactory.getLogger(StudentConteroller.class);
@Autowired
StudentConsumerService studentService;
@ResponseBody
@GetMapping("/consumer/list")
public String list(
@ApiParam(value = "学生姓名") @RequestParam(required = false) String sname,
@ApiParam(value = "年龄") @RequestParam(required = false) Integer age,
ModelMap modelMap) {
String json = null;
try {
json = studentService.getStudentList(sname, age);
} catch (Exception e) {
e.printStackTrace();
modelMap.put("ren_code", "0");
modelMap.put("ren_msg", "查询失败===>" + e);
LOGGER.error("查询失败===>" + e);
json = JSON.toJSonString(modelMap);
}
return json;
}
}
接着:创建核心启动类:
@EnableFeignClients//开启Feign调用接口
@EnableDiscoveryClient//开启客户端服务,没有这个注解会报Feign找不到对应服务的错误
@SpringBootApplication
public class ConsulConsumerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(EurekaConsumerApplication.class, args);
}
}
最后:启动项目,看到如下日志打印信息:
. ____ _ __ _ _
/\ / ___'_ __ _ _(_)_ __ __ _
( ( )___ | '_ | '_| | '_ / _` |
\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |___, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.3.RELEASE)
2018-08-09 13:49:33.195 INFO 12308 --- [ main] c.z.c.c.ConsulConsumerApplication : The following profiles are active: dev
2018-08-09 13:49:33.225 INFO 12308 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@56da52a7: startup date [Thu Aug 09 13:49:33 GMT+08:00 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@301eda63
2018-08-09 13:49:35.931 INFO 12308 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=463d6f0b-dab0-33c8-bfa5-f0bbae745006
2018-08-09 13:49:35.965 INFO 12308 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-08-09 13:49:36.011 INFO 12308 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'cn.zhangbox.consul.consumer.service.StudentConsumerService' of type [org.springframework.cloud.netflix.feign.FeignClientFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-08-09 13:49:36.102 INFO 12308 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration' of type [org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration$$EnhancerBySpringCGLIB$$44058ad0] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-08-09 13:49:36.117 INFO 12308 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$2df2e78c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-08-09 13:49:36.925 INFO 12308 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8081 (http)
2018-08-09 13:49:36.940 INFO 12308 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2018-08-09 13:49:36.942 INFO 12308 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.14
2018-08-09 13:49:37.142 INFO 12308 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]: Initializing Spring embedded WebApplicationContext
2018-08-09 13:49:37.143 INFO 12308 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3918 ms
2018-08-09 13:49:37.518 INFO 12308 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-08-09 13:49:37.528 INFO 12308 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'metricsFilter' to: [favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-09 13:49:42.932 WARN 12308 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2018-08-09 13:49:42.932 INFO 12308 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-08-09 13:49:43.089 WARN 12308 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2018-08-09 13:49:43.089 INFO 12308 --- [ main] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2018-08-09 13:49:43.339 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-08-09 13:49:43.357 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'configurationPropertiesRebinder' has been autodetected for JMX exposure
2018-08-09 13:49:43.357 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'refreshEndpoint' has been autodetected for JMX exposure
2018-08-09 13:49:43.358 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'restartEndpoint' has been autodetected for JMX exposure
2018-08-09 13:49:43.359 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'environmentManager' has been autodetected for JMX exposure
2018-08-09 13:49:43.359 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'serviceRegistryEndpoint' has been autodetected for JMX exposure
2018-08-09 13:49:43.361 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'refreshScope' has been autodetected for JMX exposure
2018-08-09 13:49:43.365 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'environmentManager': registering with JMX server as MBean [org.springframework.cloud.context.environment:name=environmentManager,type=EnvironmentManager]
2018-08-09 13:49:43.384 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'restartEndpoint': registering with JMX server as MBean [org.springframework.cloud.context.restart:name=restartEndpoint,type=RestartEndpoint]
2018-08-09 13:49:43.399 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'serviceRegistryEndpoint': registering with JMX server as MBean [org.springframework.cloud.client.serviceregistry.endpoint:name=serviceRegistryEndpoint,type=ServiceRegistryEndpoint]
2018-08-09 13:49:43.408 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'refreshScope': registering with JMX server as MBean [org.springframework.cloud.context.scope.refresh:name=refreshScope,type=RefreshScope]
2018-08-09 13:49:43.423 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'configurationPropertiesRebinder': registering with JMX server as MBean [org.springframework.cloud.context.properties:name=configurationPropertiesRebinder,context=56da52a7,type=ConfigurationPropertiesRebinder]
2018-08-09 13:49:43.429 INFO 12308 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'refreshEndpoint': registering with JMX server as MBean [org.springframework.cloud.endpoint:name=refreshEndpoint,type=RefreshEndpoint]
2018-08-09 13:49:43.430 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Registering beans for JMX exposure on startup
2018-08-09 13:49:43.722 INFO 12308 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2018-08-09 13:49:43.724 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'auditEventsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=auditEventsEndpoint]
2018-08-09 13:49:43.733 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'featuresEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=featuresEndpoint]
2018-08-09 13:49:43.742 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'requestMappingEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=requestMappingEndpoint]
2018-08-09 13:49:43.745 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'environmentEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=environmentEndpoint]
2018-08-09 13:49:43.749 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'healthEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=healthEndpoint]
2018-08-09 13:49:43.752 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'beansEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=beansEndpoint]
2018-08-09 13:49:43.754 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'infoEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=infoEndpoint]
2018-08-09 13:49:43.758 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'loggersEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=loggersEndpoint]
2018-08-09 13:49:43.768 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'metricsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=metricsEndpoint]
2018-08-09 13:49:43.771 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'traceEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=traceEndpoint]
2018-08-09 13:49:43.774 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'dumpEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=dumpEndpoint]
2018-08-09 13:49:43.777 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'autoConfigurationReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=autoConfigurationReportEndpoint]
2018-08-09 13:49:43.780 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'configurationPropertiesReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint]
2018-08-09 13:49:43.783 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'consulEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=consulEndpoint]
2018-08-09 13:49:43.785 INFO 12308 --- [ main] o.s.b.a.e.jmx.EndpointMBeanExporter : Located managed bean 'archaiusEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=archaiusEndpoint]
2018-08-09 13:49:43.786 INFO 12308 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2018-08-09 13:49:43.786 INFO 12308 --- [ main] d.s.w.p.documentationPluginsBootstrapper : Context refreshed
2018-08-09 13:49:43.876 INFO 12308 --- [ main] d.s.w.p.documentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2018-08-09 13:49:43.898 INFO 12308 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
2018-08-09 13:49:44.024 WARN 12308 --- [ main] s.d.s.w.r.p.ParameterDataTypeReader : Trying to infer dataType org.springframework.ui.ModelMap
2018-08-09 13:49:44.130 INFO 12308 --- [ main] s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2018-08-09 13:49:44.276 INFO 12308 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (http)
2018-08-09 13:49:44.287 INFO 12308 --- [ main] o.s.c.c.s.ConsulServiceRegistry : Registering service with consul: NewService{id='consul-consumer-dev-8081', name='consul-consumer', tags=[], address='192.168.1.9', port=8081, enableTagOverride=null, check=Check{script='null', interval=10s, ttl=null, http=http://192.168.1.9:8081/swagger-ui.html, tcp=null, timeout=null, deregisterCriticalServiceAfter=null, tlsSkipVerify=null}, checks=null}
2018-08-09 13:49:44.348 INFO 12308 --- [ main] c.z.c.c.ConsulConsumerApplication : Started ConsulConsumerApplication in 14.664 seconds (JVM running for 17.445)
至此consul-consumer服务提供者创建完成,浏览器输入地址:http://127.0.0.1:8081/swagger-ui.html
consul注册中心可以看到服务提供和消费者都在:
跳转看到swagger的页面并可是测试服务消费者的接口,可以看到如下页面,并点击try it out按钮,返回了正确的学生信息数据
返回数据如下:
{
"ren_code": "0",
"ren_msg": "查询成功",
"studentList": [{
"age": "17",
"birth": "2010-07-22",
"dept": "王同学学习成绩很不错",
"sex": "1",
"sname": "王同学",
"sno": 1
}, {
"age": "17",
"birth": "2010-07-22",
"dept": "李同学学习成绩很不错",
"sex": "1",
"sname": "李同学",
"sno": 2
}]
}
以上就是spring cloud基于consul实现分布式服务注册与消费的整合流程,是不是很简单,你也来小试牛刀一把吧。
写在最后欢迎关注、喜欢、和点赞后续将推出更多的spring cloud教程,敬请期待。
源码地址:SpringCloud核心教程 | 第四篇:服务注册与发现 Consul篇



