1. 簡介
上篇記錄瞭如何啓動一個服務註冊中心,本篇記錄如何發佈一個服務,並將服務註冊到註冊中心。服務的發佈是當一個服務功能完成,啓動並開始處理請求。服務註冊是將服務的相關信息註冊到註冊中心,便於服務調用者通過註冊中心發現服務,進而調用服務。
2. 代碼實現
2.1涉及的模塊
- eureka-server-singleton:服務註冊中心
- eureka-service:服務提供者
2.2 源代碼
2.2.1 Github地址
https://github.com/andyChenHuaYing/spring-cloud-demo
2.2.2 切換
Commit:Finished eureka-service
Revision Number:e1489c1e17e83e620177df7ae17b5194d0151452
spring-cloud-demo目錄下,終端執行命令:
git checkout e1489c1e17e83e620177df7ae17b5194d0151452
2.3 eureka-service
2.3.1 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">
<parent>
<artifactId>spring-cloud-finchley-demo</artifactId>
<groupId>org.oscar.scd</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eureka-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
</project>
2.3.2 application.yml
指定註冊中心地址,當前服務application name以及端口8762
server:
port: 8762
spring:
application:
name: eureka-service
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
2.3.3 EurekaServiceApplication
實例方法應返回spring.application.name + : + server.port更加直觀,後續統一優化
package org.oscar.scd.eureka.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableEurekaClient
@SpringBootApplication
public class EurekaServiceApplication {
@Value("${server.port}")
private int serverPort;
@RequestMapping("/print")
public String serverPortPrint(@RequestParam(value = "name", defaultValue = "oscar") String name) {
return "Hi " + name + " ,i am from port: " + serverPort;
}
public static void main(String[] args) {
SpringApplication.run(EurekaServiceApplication.class, args);
}
}
3. 驗證
3.1 啓動模塊
- 啓動服務註冊中心
- 啓動服務提供者
3.2 訪問服務信息界面
訪問地址:http://localhost:8761/
查看已註冊的服務,名稱爲eureka-service。
4. 思考
- 網絡連接:基於http協議,是否還有其他方式
- 數據傳輸:目前只支持http形式的通訊,是否支持其他的通訊方式如RPC
- 數據協議:是否支持多種協議,如json,hession等
5. 補充
5.1 資料
http://cloud.spring.io/spring-cloud-static/Finchley.SR1/multi/multi_spring-cloud-eureka-server.html