史上最簡單的springcloud搭建(附阿里腳手架使用)

特別說明:本文僅限於初學者,深入探討spring cloud的特性請持續關注後續博文。

不同於網上的其他教程,我們主要借用今年阿里剛發佈的腳手架(https://start.aliyun.com/),至於爲什麼使用這個腳手架,相信用過https://start.spring.io的都知道,spring自帶的這個,不做代理根本是無法正常構建的。

構建一個spring cloud項目,主要分爲三個部分:註冊中心、服務者、消費者

我們先從註冊中心開始構建,

首先進入阿里的腳手架頁面,填寫相關的項目信息,然後選擇spring cloud註冊中心的相關依賴(詳情請看下圖)

選擇Eureka Server,然後構建模板

下載之後,打開項目,按照下圖進行編輯

spring.application.name=demo
# 應用服務web訪問端口
server.port=1234
# ActuatorWeb訪問端口
management.server.port=8081
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

# spring cloud access&secret config
# 可以訪問如下地址查看: https://usercenter.console.aliyun.com/#/manage/ak
spring.cloud.alicloud.access-key=****
spring.cloud.alicloud.secret-key=****

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/

在啓動類上添加註解@EnableEurekaServer

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class DemoApplication {

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

}

啓動項目,這時候我們發現已經可以訪問到註冊中心管理頁了(訪問時不需要帶項目名,直接localhost:1234即可),此時我們的註冊中心搭建完畢。

接下來我們構建一個服務者,構建流程與上述過程類似,這不過依賴需要更改一下,這次我們選擇使用Eureka Discovery Client

下載之後打開項目,修改配置文件

#################################### common config : ####################################
spring.application.name=server
# 應用服務web訪問端口
server.port=8080
# ActuatorWeb訪問端口
management.server.port=8081
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

# spring cloud access&secret config
# 可以訪問如下地址查看: https://usercenter.console.aliyun.com/#/manage/ak
spring.cloud.alicloud.access-key=****
spring.cloud.alicloud.secret-key=****

spring.cloud.loadbalancer.ribbon.enabled=false
eureka.client.serviceUrl.defaultZone=http://localhost:1234/eureka/

不同於註冊中心,服務者的啓動類需要做以下處理(如果不做線程處理,使用啓動類無法正常啓動,但是在tomcat可以正常啓動,具體原因不詳,有知道的小夥伴可以底下留言)

package com.example.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServerApplication.class, args);
		while (true){
			try {
				Thread.sleep(Integer.MAX_VALUE);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

此時,服務者構建完成,此時刷新註冊中心管理頁面,我們發現已經顯示出一個註冊服務。

消費者的構建方式與服務者基本一致,關於消費者如何調用服務,我們將在後續博文中介紹。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章