Spring基礎:快速入門spring cloud(2):服務發現之eureka
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
Spring Cloud是Spring總多的Project中的一個,它提供了一整套的工具幫助系統架構師們在進行分散式設計的時候可以拿來即用, 在建立和釋出微服務時極為便捷和有效。本系列文章將會使用最簡單的例子和最為容易的方式來學習Spring Cloud。本文將會介紹如何使用Spring Cloud的Eureka實現服務發現。
構成
Spring Cloud由很多子專案構成,為了介紹方便,挑出一些專案中常用的進行如下構成。
具體各個Service之間的關係不再一一展示,將其粗暴地分為框架類服務(Spring Cloud服務)也業務邏輯服務兩種,各服務功能和實現簡單如下說明。
專案 | 詳細 |
---|---|
Config Service | Spring Cloud Config:統一配置管理服務 |
Dashboard Service | Hystrix Dashboard |
Api Route Service | Zuul:Api Gateway |
Discovery Service | Eureka:服務發現 |
User Service | RESTFUL的使用者相關的服務 |
Org Service | RESTFUL的組織相關的服務 |
Discovery Service
本文將會用最簡單的方式來介紹如何使用Eureka進行服務發現的,以及Spring Cloud中使用Eureka是如何方便。
Sprint Boot專案
建立一個Spring Boot專案,詳細不再介紹, 集體方法可以參看如下文件。
專案 | 詳細 |
---|---|
SPRING INITIALIZR | http://blog.csdn.net/liumiaocn/article/details/53442364 |
Eureka Server
Pom設定
需要將
<artifactId>spring-cloud-starter-eureka-server</artifactId>
加入到POM中,可以參照如下Pom示例。
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.liumiaocn.demo.springcloud</groupId> <artifactId>discoveryservice</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>discoveryservice</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Camden.BUILD-SNAPSHOT</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories></project>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
註解
加入註解EnableEurekaServer,在Spring boot的應用中只需這樣一行就將EurekaServer引入其中。
package com.liumiaocn.demo.springcloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@[email protected] class DiscoveryserviceApplication { public static void main(String[] args) { SpringApplication.run(DiscoveryserviceApplication.class, args); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
設定檔案
使用bootstrap和application兩個設定檔案來進行相關設定,入門時為了更加快速,使用最少的設定檔案和設定語句,基本上只有不可或缺的才會加上,入門之後詳細內容參看spring cloud官方文件即可。application.properties檔案的最少作如下設定即可。
server.port=8801eureka.client.register-with-eureka=falseeureka.client.fetch-registry=falseeureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
- 1
- 2
- 3
- 4
專案 | 詳細 |
---|---|
server.port | Eureka Server的Dashboard所使用的port |
eureka.client.register-with-eureka | 是否要註冊到伺服器端,因為此處為Eureka Server,所以設定為false |
eureka.client.fetch-registry | 是否從伺服器端取得註冊資訊,因為此處為Eureka Server,所以設定為false |
eureka.client.serviceUrl.defaultZone | 設定為為http://localhost:8801/eureka/,預設為8761埠。 |
啟動
2016-12-28 07:59:33.200 INFO 5228 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]c86b9e3: startup date [Wed Dec 28 07:59:33 CST 2016]; root of context hierarchy2016-12-28 07:59:33.434 INFO 5228 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring2016-12-28 07:59:33.466 INFO 5228 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$fb56a29e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.4.3.RELEASE)2016-12-28 07:59:33.902 INFO 5228 --- [ main] c.l.d.s.DiscoveryserviceApplication : No active profile set, falling back to default profiles: default2016-12-28 07:59:33.902 INFO 5228 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]35229f85: startup date [Wed Dec 28 07:59:33 CST 2016]; parent: org.spring[email protected]c86b9e32016-12-28 07:59:34.796 WARN 5228 --- [ main] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance @Configuration bean definition 'refreshScope' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.2016-12-28 07:59:34.967 INFO 5228 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=37576f2c-11e3-3d56-80ff-2435c6a59fa32016-12-28 07:59:35.030 INFO 5228 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring2016-12-28 07:59:35.139 INFO 5228 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$fb56a29e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2016-12-28 07:59:35.562 INFO 5228 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8801 (http)2016-12-28 07:59:35.578 INFO 5228 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat2016-12-28 07:59:35.578 INFO 5228 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.62016-12-28 07:59:35.687 INFO 5228 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext2016-12-28 07:59:35.687 INFO 5228 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1785 ms2016-12-28 07:59:36.248 INFO 5228 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'metricsFilter' to: [/*]2016-12-28 07:59:36.248 INFO 5228 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]2016-12-28 07:59:36.248 INFO 5228 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]2016-12-28 07:59:36.248 INFO 5228 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]2016-12-28 07:59:36.248 INFO 5228 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]2016-12-28 07:59:36.248 INFO 5228 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'webRequestTraceFilter' to: [/*]2016-12-28 07:59:36.248 INFO 5228 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'servletContainer' to urls: [/eureka/*]2016-12-28 07:59:36.248 INFO 5228 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'applicationContextIdFilter' to: [/*]2016-12-28 07:59:36.248 INFO 5228 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]2016-12-28 07:59:36.342 INFO 5228 --- [ost-startStop-1] c.s.j.s.i.a.WebApplicationImpl : Initiating Jersey application, version 'Jersey: 1.19.1 03/11/2016 02:08 PM'2016-12-28 07:59:36.404 INFO 5228 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson2016-12-28 07:59:36.404 INFO 5228 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson2016-12-28 07:59:36.514 INFO 5228 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml2016-12-28 07:59:36.514 INFO 5228 --- [ost-startStop-1] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml2016-12-28 07:59:37.230 INFO 5228 --- [ main] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING2016-12-28 07:59:37.292 INFO 5228 --- [ main] com.netflix.discovery.DiscoveryClient : Client configured to neither register nor query for data.2016-12-28 07:59:37.292 INFO 5228 --- [ main] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1482883177292 with initial instances count: 02016-12-28 07:59:37.370 INFO 5228 --- [ main] c.n.eureka.DefaultEurekaServerContext : Initializing ...2016-12-28 07:59:37.370 INFO 5228 --- [ main] c.n.eureka.cluster.PeerEurekaNodes : Adding new peer nodes [http://localhost:8761/eureka/]2016-12-28 07:59:37.682 INFO 5228 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson2016-12-28 07:59:37.682 INFO 5228 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson2016-12-28 07:59:37.682 INFO 5228 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml2016-12-28 07:59:37.682 INFO 5228 --- [ main] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml2016-12-28 07:59:37.791 INFO 5228 --- [ main] c.n.eureka.cluster.PeerEurekaNodes : Replica node URL: http://localhost:8761/eureka/2016-12-28 07:59:37.807 INFO 5228 --- [ main] c.n.e.registry.AbstractInstanceRegistry : Finished initializing remote region registries. All known remote regions: []2016-12-28 07:59:37.807 INFO 5228 --- [ main] c.n.eureka.DefaultEurekaServerContext : Initialized2016-12-28 07:59:38.103 INFO 5228 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]35229f85: startup date [Wed Dec 28 07:59:33 CST 2016]; parent: org.spring[email protected]c86b9e32016-12-28 07:59:38.228 INFO 5228 --- [ 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<java.lang.String, java.lang.Object>)2016-12-28 07:59:38.228 INFO 5228 --- [ 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<java.lang.String, java.lang.Object>)2016-12-28 07:59:38.228 INFO 5228 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)2016-12-28 07:59:38.228 INFO 5228 --- [ 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)2016-12-28 07:59:38.259 INFO 5228 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-12-28 07:59:38.259 INFO 5228 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-12-28 07:59:38.290 INFO 5228 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-12-28 07:59:38.836 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mappings || /mappings.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28 07:59:38.836 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/health || /health.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(java.security.Principal)2016-12-28 07:59:38.836 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/beans || /beans.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28 07:59:38.836 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/info || /info.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28 07:59:38.836 INFO 5228 --- [ 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()2016-12-28 07:59:38.836 INFO 5228 --- [ 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()2016-12-28 07:59:38.836 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/dump || /dump.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28 07:59:38.836 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/configprops || /configprops.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28 07:59:38.836 INFO 5228 --- [ 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()2016-12-28 07:59:38.852 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/trace || /trace.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28 07:59:38.852 INFO 5228 --- [ 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<java.lang.String, java.lang.String>)2016-12-28 07:59:38.852 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env/reset],methods=[POST]}" onto public java.util.Map<java.lang.String, java.lang.Object> org.springframework.cloud.context.environment.EnvironmentManagerMvcEndpoint.reset()2016-12-28 07:59:38.852 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)2016-12-28 07:59:38.852 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28 07:59:38.852 INFO 5228 --- [ 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.ServletException2016-12-28 07:59:38.852 INFO 5228 --- [ 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()2016-12-28 07:59:38.852 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/autoconfig || /autoconfig.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28 07:59:38.852 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/archaius || /archaius.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28 07:59:38.852 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)2016-12-28 07:59:38.852 INFO 5228 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env || /env.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()2016-12-28