spring cloud項目構建入門
技術選型
- spring cloud Hoxton.SR3
- spring boot 2.2.6.RELEASE
- eureka
- open fegin
- jdk 8
- maven
版本根據 spring cloud官網確定
1、構建maven父工程
idea 新建maven project
project 命名
修改pom屬性刪除src文件夾
2、構建eureka註冊中心
maven搭建eurekaserver
新建工程,選擇Spring Initializr,默認地址,或者修改為http://start.spring.io
配置工程信息
選擇Cloud Discovery,勾選EurekaServer,注意spring boot 版本選擇為2.2.6
配置appcation.properties
<code>server.port=8848 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka//<code>
主啟動類添加@EnableEurekaServer註解
啟動eureka
瀏覽器打開localhost:8848,顯示如下網頁,則eureka server 搭建成功
3、創建用戶服務user-server
步驟如上
maven 構建
選擇web 和eureka client
配置application.properties
<code>spring.application.name=USER-SERVER server.port=8080 eureka.client.serviceUrl.defaultZone=http://localhost:8848/eureka//<code>
主啟動添加註解 @EnableEurekaClient
先啟動eureka server
再啟動user server
進入 發現user-server 已經成功註冊
新建UserController
<code>package com.cloud.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @RequestMapping(value = "getUser") public String service(@RequestParam String userId){ String str="hello ,im user server ,userId:"+userId; return str; } }/<code>
瀏覽器訪問 http://localhost:8080/getUser?userId=1 結果如下
4、構建服務消費端 cloud-consumer
maven module 構建
配置application.properties
<code>#是指,這個服務的名稱 spring.application.name=CONSUME-SERVICE #該服務獨有的端口號 server.port=80 #下面這個是指向Eureka註冊中心,這樣就註冊成功了.. eureka.client.serviceUrl.defaultZone=http://localhost:8848/eureka/ /<code>
主啟動添加註解 @EnableEurekaClient @EnableFeignClients
新建 UserServiceClient UserController
<code>package com.cloud.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(value = "USER-SERVER") public interface UserServiceClient { @RequestMapping(value = "getUser") public String getUser(@RequestParam String userId); }/<code>
<code>package com.cloud.controller; import com.cloud.service.UserServiceClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class UserController { @Resource private UserServiceClient userServiceClient; @RequestMapping(value = "/consumer/getUser") public String getUser(@RequestParam String userId){ return userServiceClient.getUser(userId); } }/<code>
啟動cloud-consumer
訪問
至此spring-cloud 通過open fegin 調用user server 服務成功
關鍵字: web springframework spring