小米社群內測中心調整公告:向所有使用者重新開放申請許可權,改變機制
阿新 • • 發佈:2021-08-18
1、SpringCloud是什麼
2、SpringCloud與SpringBoot關係
3、SpringCloud與Dubbo的區別
4、入門案例
-
建立 Maven 工程
-
父工程依賴
<!--springcloud--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Greenwich.SR1</version> <type>pom</type> <scope>import</scope> </dependency> <!--springboot--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.4.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency>
- 服務提供方
現在提供方不僅僅只有 service 和 dao 層,還有 controller 層
- 服務消費方
消費方通過Http請求呼叫服務提供方
@Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); } ================================================= //使用 RestTemplate 遠端訪問http服務,需要先注入到spring @Autowired private RestTemplate restTemplate; private static final String REST_URL_PREFIX = "http://localhost:8081"; @RequestMapping("/consumer/dept/add") public boolean add(Dept dept){ System.out.println(dept); return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class); }
5、Eureka註冊中心
- springCloud推薦使用 Eureka,那為什麼使用註冊中心?,由上面程式碼可以看到,消費者呼叫服務時使用 "http://localhost:8081" 呼叫服務,如果服務端改變埠號或者 IP,那麼消費端也必須修改。所以不能硬編碼,可以將服務註冊到 Eureka,通過 Eureka 動態找到需要的服務。
- Eureka Server
//依賴 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> <version>1.4.6.RELEASE</version> </dependency> //application.yml配置 server: port: 7003 #Eureka配置 eureka: instance: hostname: eureka7003 #服務端名稱 client: register-with-eureka: false #是否向 eureka 註冊 fetch-registry: false #是否向 eureka 獲取資訊 service-url: defaultZone: http://localhost:7001/eureka/
- Eureka Client
//依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
//提供方 application.yml配置
spring:
application:
name: springcloud-provide
#Eureka配置,服務註冊
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
//消費方 application.yml配置
#eureka配置
eureka:
client:
register-with-eureka: false #不向eureka註冊
service-url:
defaultZone: http://localhost:7001/eureka/
//消費方使用**服務名**呼叫服務
//eureka 通過服務名訪問
private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDE";
@RequestMapping("/consumer/dept/add")
public boolean add(Dept dept){
System.out.println(dept);
return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class);
}
本文來自部落格園,作者:湊數的園丁yyds,轉載請註明原文連結:https://www.cnblogs.com/lq-404/p/15176223.html