springcloud Eureka 服務註冊與消費發現(基於springboot搭建)
阿新 • • 發佈:2018-12-24
1.首先加入Maven依賴
1.springboot的依賴
<!--Springboot--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2.springCloud服務的依賴
<!-- Eureka 服務jar包 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> <version>2.0.0.RELEASE</version> </dependency> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
2.添加註解和配置
在啟動類加上@EnableEurekaServer註解支援 maven依賴同上文一樣,
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @EnableEurekaServer //註解支援 @SpringBootApplication public class GsaEurekaServerApplication { public static void main(String[] args) { SpringApplication.run(GsaEurekaServerApplication.class, args); } }
在application.yml新增配置資訊
#配置應用名稱,Eureka裡就是服務名稱,優先順序高
spring:
application:
name: gsa-eureka-server
#服務埠
server:
port: 8181
#配置應用名稱,Eureka裡就是服務名稱
eureka:
instance:
hostname: localhost
client:
#由於該應用為註冊中心,所以設定為false,代表不向註冊中心註冊自己
register-with-eureka: false
#由於註冊中心的職責就是維護服務例項,它並不需要去檢索服務,所以也設定為false
fetch-registry: false
然後啟動當前專案,瀏覽器輸入http://localhost:8181/,就會看到如下頁面,表示啟動成功
2.微服務註冊發現
Maven依賴還是和上文Maven一樣,主要是在啟動類上加入@EnableDiscoveryClient
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GsaRestDatacenterApplication {
public static void main(String[] args) {
SpringApplication.run(GsaRestDatacenterApplication.class, args);
}
}
application.yml 配置檔案
spring:
application:
name: gsa-rest-datacenter
#埠
server:
port: 8686
#伺服器發現註冊配置
eureka:
client:
service-url:
defaultZone: http://localhost:8181/eureka/
以上這些步驟就可以了,啟動一下,就會發現在註冊中心有註冊進來的服務,前提是上一個Eureka服務不要忘記啟動
下一節會加閘道器,有了閘道器管理,你就會發現有多麼方便了,閘道器主要可以做路由分發,統一請求路徑都請求閘道器服務,然後再由閘道器分發到各個服務裡面去請求,好處是,那麼多的微服務,你如果要是加過濾,加異常處理,就不會每個服務加一堆程式碼了,就只由閘道器去加就可以了,還是很方便的,一般企業都是是 springboot+springCloud+閘道器 去管理自己的微服務