Eureka 基本教程
RestTemplate 使用
學習Euraka的同學直接滑到最下面, 這里先為初學者介紹 RestTemplate.
平時我們使用 Http 工具發送請求通常都會有兩個步驟, 先調用請求拿到響應信息, 再將響應信息通過 JSON 工具解析並轉換為實體類. 總的來說, RestTemplate 是 spring 提供的一個用來模擬瀏覽器發送請求和接收響應的一個類, 它能基於 Http 協議實現遠程調用. 但是需要注意的是, 它發送的是同步請求.
父工程依賴:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
</parent>
右鍵父工程創建新 maven 項目, 取名為 eurekademo.
項目引入依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
EurekaDemoApplicationTest.java:
@SpringBootTest
public class EurekaDemoApplicationTest {
@Test
public void testGet() {
RestTemplate restTemplate = new RestTemplate();
//模擬瀏覽器的請求頭, 很多國內免費的 api 都有這種限制, 一般我們會把以下配置請求頭的代碼寫在一個攔截器中, 通過 restTemplate.setClientHttpRequestInitializers() 配置進去
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
//節假日查詢免費 api
ResponseEntity<Holiday> forObject = restTemplate.exchange("http://timor.tech/api/holiday/info/2022-01-01", HttpMethod.GET, entity, Holiday.class);
System.out.println(forObject.getBody());
/*
//一般企業自己封裝的接口不會對外開放, 所以不需要向上面那么麻煩, 下面的代碼只是打個比方, 實際執行會報錯 == start
Holiday h1 = restTemplate.getForObject("http://timor.tech/api/holiday/info/2022-01-01", Holiday.class);
Holiday h2 = restTemplate.postForObject("http://timor.tech/api/holiday/info/2022-01-01", null, Holiday.class);
// == end
*/
}
}
Eureka 使用
注冊中心
作用: 管理項目集群而暴露的接口服務, 提供服務注冊與發現的功能.
-
服務注冊: 提供者 (暴露自己的服務給外部調用的角色) 向 Eureka 服務器注冊自己.
-
服務發現: 消費者 (去調用暴露出來的服務的角色) 從 Eureka 服務器獲取提供者的地址列表.
其中 Eureka 服務器也可以集群, 和其他 Eureka 服務器相互共享自己的資源.
接下來就開始搭建一個 Eureka 服務器.
父工程 pom 添加配置:
<properties>
<spring.cloud.version>2021.0.1</spring.cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
eurekademo 項目中添加依賴:
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
application.yml:
server:
port: 8080
spring:
application:
name: eureka-server
# eureka服務器配置, 每個屬性賦什么類型的值都可以按住 ctrl 點擊屬性名進去找到 set 操作
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka #默認服務注冊中心地址, 多個使用 ',' 隔開
register-with-eureka: false #是否注冊, 默認值 true, 由於這個項目作為 eureka 的注冊中心使用, 注冊自己會報錯, 配置其他注冊中心地址不會報錯
fetch-registry: false #是否檢索服務, 默認值 true, 基本上這個項目不會去處理業務功能, 所以也不需要檢索其他服務, 集群注冊中心的話就賦 true
server:
eviction-interval-timer-in-ms: 10000 #注冊中心清理無效節點的時間間隔, 默認為 60000L , 單位毫秒 ms
創建啟動類 EurekaDemoApplication , 注意組織名 groupId + .eurekademo 為啟動類的父包, 我的 groupId 為 com.kent
, 所以父包為 com.kent.eurekademo
:
/**
* @Title: EurekaDemoApplication
* @Description: eureka 服務器注冊中心
* @author: kent
* @date: 2022/3/16 14:53
* @Version: 1.0
*/
@SpringBootApplication
@EnableEurekaServer //boot 的特點就是需要 Enable
public class EurekaDemoApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaDemoApplication.class, args);
}
}
ok , 直接 run 起來! 啟動成功后訪問 http://127.0.0.1:8080/ 就可以看到 eureka 展示的一些基本信息. 英文看不懂的話, 最好配備一個網易有道詞典. 😄
提供者
右鍵父工程創建新 maven 項目 consumerdemo
項目引入依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
application.yml 配置:
server:
port: 15050
spring:
application:
name: consumerdemo
# 使用 eureka 暴露自身地址, 拉取其他服務地址
eureka:
client:
fetch-registry: true
register-with-eureka: true # fetch-registry 與 register-with-eureka 都為 true 表示即為提供者, 亦為消費者
service-url:
defaultZone: http://127.0.0.1:8080/eureka
eureka-server-connect-timeout-seconds: 10 # 連接注冊中心超時時間, 默認 5, 單位秒, 一般和注冊中心服務失效時間配置一致
eureka-server-read-timeout-seconds: 10 # 讀取服務列表的超時時間, 默認 8, 單位秒
instance:
#hostname: ${spring.application.name} # 主機名稱, 作用於 eureka 管理頁面服務實例列表的鏈接地址, 默認是自己電腦名, prefer-ip-address.instance.eureka=false 默認取這個
appname: ${spring.application.name} # 實例名稱, 默認使用 spring.application.name 的值, 一般不配置
prefer-ip-address: true # 使用 ip 地址定義在注冊中心的地址, 作用於 eureka 管理頁面服務實例列表的鏈接地址, 默認為 false
#ip-address: 127.0.0.1 # 主機 ip 地址, 基本上不配置, prefer-ip-address.instance.eureka=true 優先取這個
lease-renewal-interval-in-seconds: 5 # 服務續約間隔時間, 默認為 90, 單位秒
創建啟動類 ConsumerDemoApplication.java , 添加注解 @EnableEurekaClient, 那么啟動起來這個提供者就開始生效了.
消費者
創建項目的過程以及配置都和提供者一樣.
現在就是看看怎么調用, 創建一個前端控制器:
@RestController
public class HelloEurekaController {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
@GetMapping("testPort")
public String testPort() {
// 根據服務名獲取實例列表
List<ServiceInstance> serviceInstances = discoveryClient.getInstances("consumerdemo");
ServiceInstance serviceInstance = serviceInstances.get(0);
return "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort();
}
}
這里已經拿到提供者的訪問地址, 該怎么調用我想應該難不倒你們😄