SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇

Spring Cloud简介

Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中涉及的配置管理、服务发现、断路器、智能路由、微代理、控制总线、全局锁、决策竞选、分布式会话和集群状态管理等操作提供了一种简单的开发方式。

Spring Cloud包含了多个子项目(针对分布式系统中涉及的多个不同开源产品),比如:Spring Cloud ConfigSpring Cloud NetflixSpring Cloud CloudFoundrySpring Cloud AWSSpring Cloud SecuritySpring Cloud CommonsSpring Cloud ZookeeperSpring Cloud CLI等项目。

微服务架构

“微服务架构”在这几年非常的火热,以至于关于微服务架构相关的开源产品被反复的提及(比如: netflixdubbo),Spring Cloud也因Spring社区的强大知名度和影响力也被广大架构师与开发者备受关注。

那么什么是“微服务架构”呢?简单的说,微服务架构就是将一个完整的应用从数据存储开始垂直拆分成多个不同的服务,每个服务都能独立部署、独立维护、独立扩展,服务与服务间通过诸如RESTful API的方式互相调用。

对于“微服务架构”,大家在互联网可以搜索到很多相关的介绍和研究文章来进行学习和了解。也可以阅读始祖Martin Fowler的《Microservices》(中文版翻译点击查看),本文不做更多的介绍和描述。

服务治理

在简单介绍了Spring Cloud和微服务架构之后,下面回归本文的主旨内容,如何使用Spring Cloud来实现服务治理。

由于Spring Cloud为服务治理做了一层抽象接口,所以在Spring Cloud应用中可以支持多种不同的服务治理框架,比如:Netflix EurekaConsulZookeeper。在Spring Cloud服务治理抽象层的作用下,我们可以无缝地切换服务治理实现,并且不影响任何其他的服务注册、服务发现、服务调用等逻辑。

所以,下面我们通过Eureka这种种服务治理的实现来体会Spring Cloud这一层抽象所带来的好处。
下一篇介绍基于Consul的服务注册与调用。

Spring Cloud Eureka

首先,我们来尝试使用Spring Cloud Eureka来实现服务治理。

Spring Cloud EurekaSpring Cloud Netflix项目下的服务治理模块。而Spring Cloud Netflix项目是Spring Cloud的子项目之一,主要内容是对Netflix公司一系列开源产品的包装,它为Spring Boot应用提供了自配置的Netflix OSS整合。通过一些简单的注解,开发者就可以快速的在应用中配置一下常用模块并构建庞大的分布式系统。它主要提供的模块包括:服务发现(Eureka),断路器(Hystrix),智能路由(Zuul),客户端负载均衡(Ribbon)等。

下面,就来具体看看如何使用Spring Cloud Eureka实现服务治理,这里使用eureka-server为服务注册中心工程、eureka-provider服务提供者工程、eureka-consumer服务消费者工程。

准备工作

环境:

windows
jdk 8
maven 3.0
IDEA

构建工程

首先构建父工程,引入父工程依赖:



    4.0.0
    
    
        cn.zhangbox
        spring-cloud-study
        1.0-SNAPSHOT
    
    
    cn.zhangbox
    spring-cloud-eureka
    pom
    1.0-SNAPSHOT
    
    
    
        eureka-server
        eureka-provider
        eureka-consumer
    
    

父工程取名为:spring-cloud-eureka
构建子工程,分别创建工程名为:eureka-servereureka-providereureka-consumer并在pom中加入以下依赖:



    4.0.0

    
        cn.zhangbox
        spring-cloud-eureka
        1.0-SNAPSHOT
    

    cn.zhangbox
    eureka-server
    1.0.0
    jar

    eureka-server
    Spring Cloud In Action

    
        UTF-8
        1.8
    

    
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka-server
        
        
    

    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Dalston.SR1
                pom
                import
            
        
    
    

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    
    




    4.0.0

    
        cn.zhangbox
        spring-cloud-eureka
        1.0-SNAPSHOT
    

    cn.zhangbox
    eureka-provider
    0.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-eureka
        
        

        
        
            org.springframework.boot
            spring-boot-starter-web
        
        

        
        
            io.springfox
            springfox-swagger2
            2.6.1
        
        
            io.springfox
            springfox-swagger-ui
            2.6.1
        
        

        
        
            mysql
            mysql-connector-java
            runtime
        
        

        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        

        
        
            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-dependencies
                Dalston.SR1
                pom
                import
            
        
    
    

    
        eureka-provider
        
            
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
        
    




    4.0.0

    
        cn.zhangbox
        spring-cloud-eureka
        1.0-SNAPSHOT
    

    cn.zhangbox
    eureka-consumer
    0.0.1-SNAPSHOT
    jar

    eureka-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-eureka
        
        

        
        
            org.springframework.cloud
            spring-cloud-starter-feign
        
        

        
        
            org.springframework.boot
            spring-boot-starter-web
        
        

        
        
            io.springfox
            springfox-swagger2
            2.6.1
        
        
            io.springfox
            springfox-swagger-ui
            2.6.1
        
        

        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        

        
        
            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-dependencies
                Dalston.SR1
                pom
                import
            
        
    
    

    
        eureka-provider
        
            
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
        
    


工程构建完成。

服务注册中心工程配置

首先:eureka-server工程下resource目录下添加application.yml文件并加入以下配置:

#工程名称
spring:
  application:
    name: eureka-server
#选择哪一个环境的配置
#这里可以在每个环境配置redis,数据库(mysql),消息(kafka)等相关的组件的配置
  profiles:
    active: dev
#配置eureka注册中心
eureka:
  #server:
    #配置关闭自我保护模式
    #enableSelfPreservation: false
    #配置Eureka Server清理无效节点的时间间隔
    #eviction-interval-timer-in-ms: 4000
  instance:
    #配置与此实例相关联的主机名,是其他实例可以用来进行请求的准确名称
    hostname: eureka-server
    #显示服务ip地址
    preferIpAddress: true
    #获取服务的ip和端口
    instanceId: ${spring.cloud.client.ipAddress}:${server.port}
  client:
    #配置不将自己注册到eureka注册中心
    register-with-eureka: false
    #配置此客户端不获取eureka服务器注册表上的注册信息
    fetch-registry: false
    serviceUrl:
          #配置默认节点有信息,这里是获取本机的ip和端口来实现,如果不配置,默认会找8761端口,这里配置的是1001端口,因此会报错
          defaultZone: http://${spring.cloud.client.ipAddress}:${server.port}/eureka/
      
#文档块区分为三个---
---
server:
  port: 1001
spring:
  profiles: dev
#日志
logging:
  config: classpath:log/logback.xml
  path: log/eureka-server

#文档块区分为三个---
---
server:
  port: 1002
spring:
  profiles: test
#日志
logging:
  config: classpath:log/logback.xml
  path: usr/eureka-server/log/eureka-server

#文档块区分为三个---
---
server:
  port: 1003
spring:
  profiles: prod
#日志
logging:
  config: classpath:log/logback.xml
  path: usr/eureka-server/log/eureka-server

这里日志的配置不在详细说明,不知道怎么配置可以参考这篇文章:
SpringBoot进阶教程 | 第二篇:日志组件logback实现日志分级打印

其次:创建核心启动类:

@EnableEurekaServer//加上此注解表示将此工程启动后为注册中心
@SpringBootApplication
public class EurekaServerApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(EurekaServerApplication.class).web(true).run(args);
    }

}

最后:启动项目,看到如下日志打印信息:

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.3.RELEASE)

2018-07-17 15:05:53.541  INFO 7080 --- [           main] c.z.eureka.EurekaServerApplication       : The following profiles are active: dev
2018-07-17 15:05:53.588  INFO 7080 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5b22b970: startup date [Tue Jul 17 15:05:53 GMT+08:00 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@3af0a9da
2018-07-17 15:05:55.126  INFO 7080 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=cd854175-7c7f-3c0f-8597-c3d23f037104
2018-07-17 15:05:55.147  INFO 7080 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-07-17 15:05:55.247  INFO 7080 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration' of type [org.springframework.cloud.netflix.metrics.MetricsInterceptorConfiguration$MetricsRestTemplateConfiguration$$EnhancerBySpringCGLIB$$a90c774] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-07-17 15:05:55.259  INFO 7080 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$f47e2430] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-07-17 15:05:55.658  INFO 7080 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 1001 (http)
2018-07-17 15:05:55.670  INFO 7080 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2018-07-17 15:05:55.672  INFO 7080 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.14
2018-07-17 15:05:55.946  INFO 7080 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-07-17 15:05:55.947  INFO 7080 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2359 ms
2018-07-17 15:05:57.669  INFO 7080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'metricsFilter' to: [/*]
2018-07-17 15:05:57.680  INFO 7080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-17 15:05:57.681  INFO 7080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-17 15:05:57.681  INFO 7080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-17 15:05:57.681  INFO 7080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-07-17 15:05:57.682  INFO 7080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webRequestTraceFilter' to: [/*]
2018-07-17 15:05:57.683  INFO 7080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'servletContainer' to urls: [/eureka/*]
2018-07-17 15:05:57.683  INFO 7080 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'applicationContextIdFilter' to: [/*]
2018-07-17 15:05:57.683  INFO 7080 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-07-17 15:05:58.056  INFO 7080 --- [ost-startStop-1] c.s.j.s.i.a.WebApplicationImpl           : Initiating Jersey application, version 'Jersey: 1.19.1 03/11/2016 02:08 PM'
2018-07-17 15:05:58.376  INFO 7080 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2018-07-17 15:05:58.378  INFO 7080 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2018-07-17 15:05:58.617  INFO 7080 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2018-07-17 15:05:58.618  INFO 7080 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2018-07-17 15:06:00.945  INFO 7080 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5b22b970: startup date [Tue Jul 17 15:05:53 GMT+08:00 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@3af0a9da
2018-07-17 15:06:02.200  INFO 7080 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-07-17 15:06:02.202  INFO 7080 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-07-17 15:06:02.209  INFO 7080 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String org.springframework.cloud.netflix.eureka.server.EurekaController.status(javax.servlet.http.HttpServletRequest,java.util.Map)
2018-07-17 15:06:02.209  INFO 7080 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/lastn],methods=[GET]}" onto public java.lang.String org.springframework.cloud.netflix.eureka.server.EurekaController.lastn(javax.servlet.http.HttpServletRequest,java.util.Map)
2018-07-17 15:06:02.257  INFO 7080 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-17 15:06:02.258  INFO 7080 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-17 15:06:02.590  INFO 7080 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-17 15:06:04.453  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/logfile || /logfile.json],methods=[GET || HEAD]}" onto public void org.springframework.boot.actuate.endpoint.mvc.LogFileMvcEndpoint.invoke(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws javax.servlet.ServletException,java.io.IOException
2018-07-17 15:06:04.454  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/archaius || /archaius.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.456  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/health || /health.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(javax.servlet.http.HttpServletRequest,java.security.Principal)
2018-07-17 15:06:04.457  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/auditevents || /auditevents.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public org.springframework.http.ResponseEntity org.springframework.boot.actuate.endpoint.mvc.AuditEventsMvcEndpoint.findByPrincipalAndAfterAndType(java.lang.String,java.util.Date,java.lang.String)
2018-07-17 15:06:04.458  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/beans || /beans.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.460  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/pause || /pause.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.endpoint.GenericPostableMvcEndpoint.invoke()
2018-07-17 15:06:04.461  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/service-registry/instance-status],methods=[GET]}" onto public org.springframework.http.ResponseEntity org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint.getStatus()
2018-07-17 15:06:04.461  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/service-registry/instance-status],methods=[POST]}" onto public org.springframework.http.ResponseEntity org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint.setStatus(java.lang.String)
2018-07-17 15:06:04.462  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/autoconfig || /autoconfig.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.463  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/metrics/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2018-07-17 15:06:04.463  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.466  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/info || /info.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.468  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/loggers/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.LoggersMvcEndpoint.get(java.lang.String)
2018-07-17 15:06:04.468  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/loggers/{name:.*}],methods=[POST],consumes=[application/vnd.spring-boot.actuator.v1+json || application/json],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.LoggersMvcEndpoint.set(java.lang.String,java.util.Map)
2018-07-17 15:06:04.468  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/loggers || /loggers.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.469  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/resume || /resume.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.endpoint.GenericPostableMvcEndpoint.invoke()
2018-07-17 15:06:04.471  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/dump || /dump.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.472  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.context.environment.EnvironmentManagerMvcEndpoint.value(java.util.Map)
2018-07-17 15:06:04.473  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env/reset],methods=[POST]}" onto public java.util.Map org.springframework.cloud.context.environment.EnvironmentManagerMvcEndpoint.reset()
2018-07-17 15:06:04.473  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/mappings || /mappings.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.474  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/features || /features.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.474  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/trace || /trace.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.475  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env/{name:.*}],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)
2018-07-17 15:06:04.476  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env || /env.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.478  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/restart || /restart.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.context.restart.RestartMvcEndpoint.invoke()
2018-07-17 15:06:04.479  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/heapdump || /heapdump.json],methods=[GET],produces=[application/octet-stream]}" onto public void org.springframework.boot.actuate.endpoint.mvc.HeapdumpMvcEndpoint.invoke(boolean,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.io.IOException,javax.servlet.ServletException
2018-07-17 15:06:04.480  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/configprops || /configprops.json],methods=[GET],produces=[application/vnd.spring-boot.actuator.v1+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2018-07-17 15:06:04.480  INFO 7080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/refresh || /refresh.json],methods=[POST]}" onto public java.lang.Object org.springframework.cloud.endpoint.GenericPostableMvcEndpoint.invoke()
2018-07-17 15:06:04.762  INFO 7080 --- [           main] o.s.ui.freemarker.SpringTemplateLoader   : SpringTemplateLoader for FreeMarker: using resource loader [org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5b22b970: startup date [Tue Jul 17 15:05:53 GMT+08:00 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@3af0a9da] and template loader path [classpath:/templates/]
2018-07-17 15:06:04.763  INFO 7080 --- [           main] o.s.w.s.v.f.FreeMarkerConfigurer         : ClassTemplateLoader for Spring macros added to FreeMarker configuration
2018-07-17 15:06:06.416  WARN 7080 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2018-07-17 15:06:06.440  INFO 7080 --- [           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-07-17 15:06:06.871  WARN 7080 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2018-07-17 15:06:06.872  INFO 7080 --- [           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-07-17 15:06:07.545  INFO 7080 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2018-07-17 15:06:07.746  INFO 7080 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2018-07-17 15:06:07.746  INFO 7080 --- [           main] com.netflix.discovery.DiscoveryClient    : Client configured to neither register nor query for data.
2018-07-17 15:06:07.996  INFO 7080 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1531811167765 with initial instances count: 0
2018-07-17 15:06:08.140  INFO 7080 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initializing ...
2018-07-17 15:06:08.143  WARN 7080 --- [           main] c.n.eureka.cluster.PeerEurekaNodes       : The replica size seems to be empty. Check the route 53 DNS Registry
2018-07-17 15:06:08.159  INFO 7080 --- [           main] c.n.e.registry.AbstractInstanceRegistry  : Finished initializing remote region registries. All known remote regions: []
2018-07-17 15:06:08.159  INFO 7080 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initialized
2018-07-17 15:06:08.443  INFO 7080 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-07-17 15:06:08.458  INFO 7080 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'environmentManager' has been autodetected for JMX exposure
2018-07-17 15:06:08.461  INFO 7080 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'configurationPropertiesRebinder' has been autodetected for JMX exposure
2018-07-17 15:06:08.462  INFO 7080 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'refreshEndpoint' has been autodetected for JMX exposure
2018-07-17 15:06:08.463  INFO 7080 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'restartEndpoint' has been autodetected for JMX exposure
2018-07-17 15:06:08.464  INFO 7080 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'serviceRegistryEndpoint' has been autodetected for JMX exposure
2018-07-17 15:06:08.465  INFO 7080 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'refreshScope' has been autodetected for JMX exposure
2018-07-17 15:06:08.468  INFO 7080 --- [           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-07-17 15:06:08.492  INFO 7080 --- [           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-07-17 15:06:08.574  INFO 7080 --- [           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-07-17 15:06:08.586  INFO 7080 --- [           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-07-17 15:06:08.603  INFO 7080 --- [           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=5b22b970,type=ConfigurationPropertiesRebinder]
2018-07-17 15:06:08.608  INFO 7080 --- [           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-07-17 15:06:08.609  INFO 7080 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Registering beans for JMX exposure on startup
2018-07-17 15:06:08.979  INFO 7080 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2018-07-17 15:06:08.980  INFO 7080 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application eureka-server with eureka with status UP
2018-07-17 15:06:08.983  INFO 7080 --- [           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-07-17 15:06:08.991  INFO 7080 --- [           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-07-17 15:06:08.998  INFO 7080 --- [           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-07-17 15:06:09.000  INFO 7080 --- [           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-07-17 15:06:09.002  INFO 7080 --- [           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-07-17 15:06:09.005  INFO 7080 --- [           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-07-17 15:06:09.007  INFO 7080 --- [           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-07-17 15:06:09.010  INFO 7080 --- [           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-07-17 15:06:09.017  INFO 7080 --- [           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-07-17 15:06:09.019  INFO 7080 --- [           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-07-17 15:06:09.021  INFO 7080 --- [           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-07-17 15:06:09.023  INFO 7080 --- [           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-07-17 15:06:09.026  INFO 7080 --- [           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-07-17 15:06:09.028  INFO 7080 --- [           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-07-17 15:06:09.039  INFO 7080 --- [      Thread-42] o.s.c.n.e.server.EurekaServerBootstrap   : Setting the eureka configuration..
2018-07-17 15:06:09.040  INFO 7080 --- [      Thread-42] o.s.c.n.e.server.EurekaServerBootstrap   : Eureka data center value eureka.datacenter is not set, defaulting to default
2018-07-17 15:06:09.040  INFO 7080 --- [      Thread-42] o.s.c.n.e.server.EurekaServerBootstrap   : Eureka environment value eureka.environment is not set, defaulting to test
2018-07-17 15:06:09.109  INFO 7080 --- [      Thread-42] o.s.c.n.e.server.EurekaServerBootstrap   : isAws returned false
2018-07-17 15:06:09.111  INFO 7080 --- [      Thread-42] o.s.c.n.e.server.EurekaServerBootstrap   : Initialized server context
2018-07-17 15:06:09.111  INFO 7080 --- [      Thread-42] c.n.e.r.PeerAwareInstanceRegistryImpl    : Got 1 instances from neighboring DS node
2018-07-17 15:06:09.111  INFO 7080 --- [      Thread-42] c.n.e.r.PeerAwareInstanceRegistryImpl    : Renew threshold is: 1
2018-07-17 15:06:09.111  INFO 7080 --- [      Thread-42] c.n.e.r.PeerAwareInstanceRegistryImpl    : Changing status to UP
2018-07-17 15:06:09.118  INFO 7080 --- [      Thread-42] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2018-07-17 15:06:09.181  INFO 7080 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 1001 (http)
2018-07-17 15:06:09.183  INFO 7080 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 1001
2018-07-17 15:06:09.189  INFO 7080 --- [           main] c.z.eureka.EurekaServerApplication       : Started EurekaServerApplication in 17.898 seconds (JVM running for 21.087)
2018-07-17 15:06:13.112  INFO 7080 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms
2018-07-17 15:06:17.112  INFO 7080 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms
2018-07-17 15:06:21.173  INFO 7080 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 61ms
2018-07-17 15:06:21.385  INFO 7080 --- [nio-1001-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-07-17 15:06:21.386  INFO 7080 --- [nio-1001-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2018-07-17 15:06:21.435  INFO 7080 --- [nio-1001-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 49 ms
2018-07-17 15:06:22.438  WARN 7080 --- [nio-1001-exec-2] c.n.e.registry.AbstractInstanceRegistry  : DS: Registry: lease doesn't exist, registering resource: EUREKA-PROVIDER - 10.25.26.144:8080
2018-07-17 15:06:22.439  WARN 7080 --- [nio-1001-exec-2] c.n.eureka.resources.InstanceResource    : Not Found (Renew): EUREKA-PROVIDER - 10.25.26.144:8080
2018-07-17 15:06:22.564  INFO 7080 --- [nio-1001-exec-3] c.n.e.registry.AbstractInstanceRegistry  : Registered instance EUREKA-PROVIDER/10.25.26.144:8080 with status UP (replication=false)
2018-07-17 15:06:25.173  INFO 7080 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms
2018-07-17 15:06:29.173  INFO 7080 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms
2018-07-17 15:06:31.169  WARN 7080 --- [nio-1001-exec-4] c.n.e.registry.AbstractInstanceRegistry  : DS: Registry: lease doesn't exist, registering resource: UNKNOWN - 10.25.26.144:8081
2018-07-17 15:06:31.169  WARN 7080 --- [nio-1001-exec-4] c.n.eureka.resources.InstanceResource    : Not Found (Renew): UNKNOWN - 10.25.26.144:8081
2018-07-17 15:06:31.198  INFO 7080 --- [nio-1001-exec-6] c.n.e.registry.AbstractInstanceRegistry  : Registered instance UNKNOWN/10.25.26.144:8081 with status UP (replication=false)

至此eureka注册中心创建完成,浏览器输入地址:http://localhost:1001/
可以看到如下页面,表示服务启动OK

SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇_第1张图片
图片.png

这里这看到还没有服务暴露出来,是因为还没创建服务提供者工程。

服务提供者工程配置

这里服务提供者是使用之前SpringBoot进阶教程 | 第三篇:整合Druid连接池以及Druid监控改造而来,这里一样的部分就不再重复说明,下面将说明新增的部分。
首先:修改application.yml配置为如下:

#公共配置
server:
    port: 80
    tomcat:
      uri-encoding: UTF-8
spring:
  application:
      #服务名称,更关键,使用feign进行服务消费将以此为依据
      name: eureka-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

#配置eureka获取服务地址,这里使用的是本地注册中心
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1001/eureka/
  #配置Swagger相关信息
  instance:
      prefer-ip-address: true
      instanceId: ${spring.cloud.client.ipAddress}:${server.port}
      status-page-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:mapper/*.xml
  # 开启驼峰匹配
  mapUnderscoreToCamelCase: true

---
#开发环境配置
server:
  #端口
  port: 8080
spring:
  profiles: dev
  # 数据源配置
  datasource:
    url: jdbc:mysql://101.132.66.175:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true
    username: root
    password: 123456
#日志
logging:
  config: classpath:log/logback.xml
  path: log/eureka-provider

---
#测试环境配置
server:
  #端口
  port: 80
spring:
  profiles: test
  # 数据源配置
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/eureka-provider?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true
    username: root
    password: 123456
#日志
logging:
  config: classpath:log/logback.xml
  path: /home/log/eureka-provider

---
#生产环境配置
server:
  #端口
  port: 8080
spring:
  profiles: prod
  # 数据源配置
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/eureka-provider?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true
    username: root
    password: 123456
#日志
logging:
  config: classpath:log/logback.xml
  path: /home/log/eureka-provider

其次: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.provider.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();
    }

}

这里如果不会使用swagger的整合可以参考这篇文章:
SpringBoot非官方教程 | 第十一篇:SpringBoot集成swagger2,构建优雅的Restful API

接着:创建核心启动类:

@EnableDiscoveryClient //使用该注解将注册服务到eureka
@SpringBootApplication
@MapperScan("cn.zhangbox.eureka.provider.dao")//配置mybatis接口包扫描
public class EurekaProviderApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(EurekaProviderApplication.class, args);
    }
}

最后:启动项目,看到如下日志打印信息:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.3.RELEASE)

2018-07-17 15:29:29.267  INFO 12312 --- [           main] c.z.e.p.EurekaProviderApplication        : The following profiles are active: dev
2018-07-17 15:29:29.295  INFO 12312 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@51827393: startup date [Tue Jul 17 15:29:29 GMT+08:00 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@4241e0f4
2018-07-17 15:29:30.902  INFO 12312 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'filterRegistrationBean' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=druidDBConfig; factoryMethodName=filterRegistrationBean; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [cn/zhangbox/eureka/provider/config/DruidDBConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=com.alibaba.druid.spring.boot.autoconfigure.stat.DruidWebStatFilterConfiguration; factoryMethodName=filterRegistrationBean; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/alibaba/druid/spring/boot/autoconfigure/stat/DruidWebStatFilterConfiguration.class]]
2018-07-17 15:29:31.251  INFO 12312 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=608dd1ca-975a-302d-aa26-cd8dca769951
2018-07-17 15:29:31.277  INFO 12312 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-07-17 15:29:31.389  INFO 12312 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d6e9b9c7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-07-17 15:29:31.449  INFO 12312 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$f303bcc4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-07-17 15:29:32.818  INFO 12312 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-07-17 15:29:32.829  INFO 12312 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2018-07-17 15:29:32.830  INFO 12312 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.14
2018-07-17 15:29:33.250  INFO 12312 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-07-17 15:29:33.250  INFO 12312 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3955 ms
2018-07-17 15:29:33.605  INFO 12312 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'statViewServlet' to [/druid/*]
2018-07-17 15:29:33.607  INFO 12312 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-07-17 15:29:33.608  INFO 12312 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'statViewServlet' to [/druid/*]
2018-07-17 15:29:33.608  INFO 12312 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet statViewServlet was not registered (possibly already registered?)
2018-07-17 15:29:33.614  INFO 12312 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-17 15:29:33.614  INFO 12312 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-17 15:29:33.614  INFO 12312 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-17 15:29:33.614  INFO 12312 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-07-17 15:29:33.615  INFO 12312 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webStatFilter' to urls: [/*]
2018-07-17 15:29:36.473  INFO 12312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/student/list],methods=[GET]}" onto public java.lang.String cn.zhangbox.eureka.provider.controller.StudentConteroller.list(java.lang.String,java.lang.Integer,org.springframework.ui.ModelMap)
2018-07-17 15:29:36.475  INFO 12312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/v2/api-docs],methods=[GET],produces=[application/json || application/hal+json]}" onto public org.springframework.http.ResponseEntity springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)
2018-07-17 15:29:36.478  INFO 12312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/swagger-resources/configuration/ui]}" onto org.springframework.http.ResponseEntity springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
2018-07-17 15:29:36.479  INFO 12312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/swagger-resources]}" onto org.springframework.http.ResponseEntity> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
2018-07-17 15:29:36.480  INFO 12312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/swagger-resources/configuration/security]}" onto org.springframework.http.ResponseEntity springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
2018-07-17 15:29:36.483  INFO 12312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-07-17 15:29:36.483  INFO 12312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-07-17 15:29:37.292  INFO 12312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@51827393: startup date [Tue Jul 17 15:29:29 GMT+08:00 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@4241e0f4
2018-07-17 15:29:37.651  INFO 12312 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-17 15:29:37.651  INFO 12312 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-17 15:29:37.717  INFO 12312 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-17 15:29:38.371  WARN 12312 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2018-07-17 15:29:38.385  INFO 12312 --- [           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-07-17 15:29:38.390  WARN 12312 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2018-07-17 15:29:38.391  INFO 12312 --- [           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-07-17 15:29:38.619  INFO 12312 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-07-17 15:29:38.622  INFO 12312 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'statFilter' has been autodetected for JMX exposure
2018-07-17 15:29:38.622  INFO 12312 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-07-17 15:29:38.631  INFO 12312 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'environmentManager' has been autodetected for JMX exposure
2018-07-17 15:29:38.633  INFO 12312 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'configurationPropertiesRebinder' has been autodetected for JMX exposure
2018-07-17 15:29:38.634  INFO 12312 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'refreshScope' has been autodetected for JMX exposure
2018-07-17 15:29:38.638  INFO 12312 --- [           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-07-17 15:29:38.942  INFO 12312 --- [           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-07-17 15:29:38.955  INFO 12312 --- [           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=51827393,type=ConfigurationPropertiesRebinder]
2018-07-17 15:29:38.963  INFO 12312 --- [           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-07-17 15:29:38.965  INFO 12312 --- [           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-07-17 15:29:39.410  INFO 12312 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2018-07-17 15:29:39.418  INFO 12312 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2018-07-17 15:29:39.548  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2018-07-17 15:29:40.130  INFO 12312 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2018-07-17 15:29:40.131  INFO 12312 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2018-07-17 15:29:40.256  INFO 12312 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2018-07-17 15:29:40.256  INFO 12312 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2018-07-17 15:29:41.457  INFO 12312 --- [           main] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2018-07-17 15:29:41.579  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Disable delta property : false
2018-07-17 15:29:41.579  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Single vip registry refresh property : null
2018-07-17 15:29:41.579  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Force full registry fetch : false
2018-07-17 15:29:41.579  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Application is null : false
2018-07-17 15:29:41.579  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Registered Applications size is zero : true
2018-07-17 15:29:41.579  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Application version is -1: true
2018-07-17 15:29:41.579  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Getting all instance registry info from the eureka server
2018-07-17 15:29:42.334  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : The response status is 200
2018-07-17 15:29:42.336  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Starting heartbeat executor: renew interval is: 30
2018-07-17 15:29:42.339  INFO 12312 --- [           main] c.n.discovery.InstanceInfoReplicator     : InstanceInfoReplicator onDemand update allowed rate per min is 4
2018-07-17 15:29:42.344  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1531812582343 with initial instances count: 0
2018-07-17 15:29:42.364  INFO 12312 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application eureka-provider with eureka with status UP
2018-07-17 15:29:42.365  INFO 12312 --- [           main] com.netflix.discovery.DiscoveryClient    : Saw local status change event StatusChangeEvent [timestamp=1531812582365, current=UP, previous=STARTING]
2018-07-17 15:29:42.367  INFO 12312 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_EUREKA-PROVIDER/10.25.26.144:8080: registering service...
2018-07-17 15:29:42.369  INFO 12312 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2018-07-17 15:29:42.369  INFO 12312 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2018-07-17 15:29:42.450  INFO 12312 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2018-07-17 15:29:42.575  INFO 12312 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_EUREKA-PROVIDER/10.25.26.144:8080 - registration status: 204
2018-07-17 15:29:42.741  INFO 12312 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2018-07-17 15:29:42.849  WARN 12312 --- [           main] s.d.s.w.r.p.ParameterDataTypeReader      : Trying to infer dataType org.springframework.ui.ModelMap
2018-07-17 15:29:43.087  INFO 12312 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-07-17 15:29:43.088  INFO 12312 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8080
2018-07-17 15:29:43.094  INFO 12312 --- [           main] c.z.e.p.EurekaProviderApplication        : Started EurekaProviderApplication in 16.419 seconds (JVM running for 21.462)

至此eureka-provider服务提供者创建完成,浏览器输入地址:http://localhost:1001/
可以看到如下页面,表示服务注册OK

SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇_第2张图片
图片.png

点击 Status下的 ip后可以跳转看到 swagger的页面并可是测试服务提供者的接口,如下:
SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇_第3张图片
图片.png

服务消费者工程配置

这里构建的工程名为eureka-consumer,上文已经构建了工程但是没有创建目录,这里只需要在java目录下创建configcontrollerservice,包即可,这里服务的消费是通过feign来进行服务调用的,后面会有专门以篇文章来讲feign
首先:eureka-consumer工程下resource目录下添加application.yml文件并加入以下配置:

#公共配置
server:
    port: 80
    tomcat:
      uri-encoding: UTF-8
spring:
  #服务名称,更关键,使用feign进行服务消费将以此为依据
  application:
     name: eureka-consumer
  #激活哪一个环境的配置文件
  profiles:
    active: dev

#配置eureka获取服务地址,这里使用的是本地注册中心
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1001/eureka/
  #配置instance相关信息
  instance:
      prefer-ip-address: true
      instanceId: ${spring.cloud.client.ipAddress}:${server.port}
      status-page-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/eureka-consumer

---
#测试环境配置
server:
  #端口
  port: 8082
spring:
  profiles: test
#日志
logging:
  config: classpath:log/logback.xml
  path: /home/log/eureka-consumer

---
#生产环境配置
server:
  #端口
  port: 8083
spring:
  profiles: prod
#日志
logging:
  config: classpath:log/logback.xml
  path: /home/log/eureka-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 = "eureka-provider")
public interface StudentConsumerService {

    /**
     * 查询所有的学生信息
     *
     * @param sname
     * @param age
     * @return
     */
    @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;

    /**
     * 查询所有的学生信息
     *
     * @param sname
     * @param age
     * @param modelMap
     * @return
     */
    @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 EurekaConsumerApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(EurekaConsumerApplication.class, args);
    }
}

最后:启动项目,看到如下日志打印信息:

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.3.RELEASE)

2018-07-17 15:56:10.446  INFO 9400 --- [           main] c.z.e.c.EurekaConsumerApplication        : The following profiles are active: dev
2018-07-17 15:56:10.480  INFO 9400 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7a799159: startup date [Tue Jul 17 15:56:10 GMT+08:00 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@3b8f0a79
2018-07-17 15:56:11.536  INFO 9400 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=6ee65f72-d692-3f45-bb25-4625a69b17da
2018-07-17 15:56:11.558  INFO 9400 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-07-17 15:56:11.590  INFO 9400 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'cn.zhangbox.eureka.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-07-17 15:56:11.640  INFO 9400 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$89a7f8be] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-07-17 15:56:12.196  INFO 9400 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8081 (http)
2018-07-17 15:56:12.265  INFO 9400 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2018-07-17 15:56:12.271  INFO 9400 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.14
2018-07-17 15:56:12.658  INFO 9400 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-07-17 15:56:12.658  INFO 9400 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2178 ms
2018-07-17 15:56:12.841  INFO 9400 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-07-17 15:56:12.847  INFO 9400 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-17 15:56:12.881  INFO 9400 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-17 15:56:12.881  INFO 9400 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-17 15:56:12.881  INFO 9400 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-07-17 15:56:12.985  INFO 9400 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6723610b: startup date [Tue Jul 17 15:56:12 GMT+08:00 2018]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7a799159
2018-07-17 15:56:13.039  INFO 9400 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-07-17 15:56:13.898  INFO 9400 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/student/consumer/list],methods=[GET]}" onto public java.lang.String cn.zhangbox.eureka.consumer.controller.StudentConteroller.list(java.lang.String,java.lang.Integer,org.springframework.ui.ModelMap)
2018-07-17 15:56:13.900  INFO 9400 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/v2/api-docs],methods=[GET],produces=[application/json || application/hal+json]}" onto public org.springframework.http.ResponseEntity springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)
2018-07-17 15:56:13.902  INFO 9400 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/swagger-resources/configuration/ui]}" onto org.springframework.http.ResponseEntity springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
2018-07-17 15:56:13.903  INFO 9400 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/swagger-resources]}" onto org.springframework.http.ResponseEntity> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
2018-07-17 15:56:13.904  INFO 9400 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/swagger-resources/configuration/security]}" onto org.springframework.http.ResponseEntity springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
2018-07-17 15:56:13.907  INFO 9400 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-07-17 15:56:13.908  INFO 9400 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-07-17 15:56:14.482  INFO 9400 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7a799159: startup date [Tue Jul 17 15:56:10 GMT+08:00 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@3b8f0a79
2018-07-17 15:56:14.555  INFO 9400 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-17 15:56:14.555  INFO 9400 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-17 15:56:14.643  INFO 9400 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-17 15:56:15.188  WARN 9400 --- [           main] o.s.c.n.a.ArchaiusAutoConfiguration      : No spring.application.name found, defaulting to 'application'
2018-07-17 15:56:15.218  WARN 9400 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2018-07-17 15:56:15.218  INFO 9400 --- [           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-07-17 15:56:15.223  WARN 9400 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2018-07-17 15:56:15.223  INFO 9400 --- [           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-07-17 15:56:15.373  INFO 9400 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-07-17 15:56:15.383  INFO 9400 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'environmentManager' has been autodetected for JMX exposure
2018-07-17 15:56:15.385  INFO 9400 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'configurationPropertiesRebinder' has been autodetected for JMX exposure
2018-07-17 15:56:15.387  INFO 9400 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'refreshScope' has been autodetected for JMX exposure
2018-07-17 15:56:15.391  INFO 9400 --- [           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-07-17 15:56:15.428  INFO 9400 --- [           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-07-17 15:56:15.442  INFO 9400 --- [           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=7a799159,type=ConfigurationPropertiesRebinder]
2018-07-17 15:56:15.562  INFO 9400 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2018-07-17 15:56:15.570  INFO 9400 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2018-07-17 15:56:15.634  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2018-07-17 15:56:16.225  INFO 9400 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2018-07-17 15:56:16.225  INFO 9400 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2018-07-17 15:56:16.345  INFO 9400 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2018-07-17 15:56:16.346  INFO 9400 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2018-07-17 15:56:16.826  INFO 9400 --- [           main] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2018-07-17 15:56:16.965  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Disable delta property : false
2018-07-17 15:56:16.966  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Single vip registry refresh property : null
2018-07-17 15:56:16.966  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Force full registry fetch : false
2018-07-17 15:56:16.966  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Application is null : false
2018-07-17 15:56:16.966  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Registered Applications size is zero : true
2018-07-17 15:56:16.967  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Application version is -1: true
2018-07-17 15:56:16.967  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Getting all instance registry info from the eureka server
2018-07-17 15:56:17.184  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : The response status is 200
2018-07-17 15:56:17.186  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Starting heartbeat executor: renew interval is: 30
2018-07-17 15:56:17.189  INFO 9400 --- [           main] c.n.discovery.InstanceInfoReplicator     : InstanceInfoReplicator onDemand update allowed rate per min is 4
2018-07-17 15:56:17.195  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1531814177194 with initial instances count: 1
2018-07-17 15:56:17.218  INFO 9400 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application unknown with eureka with status UP
2018-07-17 15:56:17.219  INFO 9400 --- [           main] com.netflix.discovery.DiscoveryClient    : Saw local status change event StatusChangeEvent [timestamp=1531814177219, current=UP, previous=STARTING]
2018-07-17 15:56:17.221  INFO 9400 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_UNKNOWN/10.25.26.144:8081: registering service...
2018-07-17 15:56:17.222  INFO 9400 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2018-07-17 15:56:17.223  INFO 9400 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2018-07-17 15:56:17.261  INFO 9400 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_UNKNOWN/10.25.26.144:8081 - registration status: 204
2018-07-17 15:56:17.280  INFO 9400 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2018-07-17 15:56:17.305  INFO 9400 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2018-07-17 15:56:17.379  WARN 9400 --- [           main] s.d.s.w.r.p.ParameterDataTypeReader      : Trying to infer dataType org.springframework.ui.ModelMap
2018-07-17 15:56:17.614  INFO 9400 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (http)
2018-07-17 15:56:17.616  INFO 9400 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8081
2018-07-17 15:56:17.621  INFO 9400 --- [           main] c.z.e.c.EurekaConsumerApplication        : Started EurekaConsumerApplication in 9.852 seconds (JVM running for 12.176)

至此eureka-consumer服务提供者创建完成,浏览器输入地址:http://127.0.0.1:8081/swagger-ui.html
同样也可以点击eureka控制台中ApplicationEUREKA-CONSUMERStatus下的ip后可以跳转看到swagger的页面并可是测试服务消费者的接口,可以看到如下页面,并点击try it out按钮,返回了正确的学生信息数据

SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇_第4张图片
图片.png

返回数据如下:
SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇_第5张图片
图片.png

{
    "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基于eurka实现分布式服务注册与消费的整合流程,是不是很简单,你也来小试牛刀一把吧。

源码地址:

SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇

写在最后

欢迎关注喜欢、和点赞后续将推出更多的思维导图学习文章,敬请期待。
欢迎关注我的微信公众号获取更多更全的学习资源,视频资料,技术干货!

欢迎扫码关注

公众号回复“学习”,拉你进程序员技术讨论群干货资源第一时间分享。

公众号回复“视频”,领取800GJava视频学习资源。

公众号回复“全栈”,领取1T前端Java产品经理微信小程序Python等资源合集大放送。

公众号回复“慕课”,领取1T慕课实战学习资源。

公众号回复“实战”,领取750G项目实战学习资源。

公众号回复“面试”,领取20G面试实战学习资源。

你可能感兴趣的:(SpringCloud核心教程 | 第三篇:服务注册与发现 Eureka篇)