上文提到的服務消費者採用的是RestTemplate+ribbon
(實現負載均衡) 目前,在Spring cloud
中服務之間經過restful方式
調用有兩種方式java
delete()
在特定的URL上對資源執行HTTP DELETE操做exchange()
在URL上執行特定的HTTP方法,返回包含對象的ResponseEntity,這個對象是從響應體中映射獲得的execute()
在URL上執行特定的HTTP方法,返回一個從響應體映射獲得的對象getForEntity()
發送一個HTTPGET請求,返回的ResponseEntity包含了響應體所映射成的對象getForObject()
發送一個HTTP GET請求,返回的請求體將映射爲一個對象postForEntity()
POST數據到一個URL,返回包含一個對象的ResponseEntity,這個對象是從響應體中映射獲得的postForObject()
POST 數據到一個URL,返回根據響應體匹配造成的對象headForHeaders()
發送HTTP HEAD請求,返回包含特定資源URL的HTTP頭optionsForAllow()
發送HTTP OPTIONS請求,返回對特定URL的Allow頭信息postForLocation()
POST 數據到一個URL,返回新建立資源的URLput()
PUT 資源到特定的URL聲明式
的僞Http客戶端,它使得寫Http客戶端變得更簡單。 使用Feign,只須要建立一個接口並註解,它具備可插拔的註解特性
,可以使用Feign 註解和JAX-RS註解
,Feign支持可插拔
的編碼器和解碼器,Feign默認集成了Ribbon
,並和Eureka結合
,默認實現了負載均衡
的效果。JAX-WS
:Java API for XML Web Services,規範是一組XML web services的JAVA API,容許開發者能夠選擇RPC-oriented或者message-oriented 來實現本身的web services。以動詞爲中心,指定的是每次執行函數(RPC
)。JAX-RS
:Java API for RESTful Web Services,以名詞爲中心,每次執行的時候指的是資源(REST
)。Feign特性git
Feign
能幹Ribbon
和Hystrix
的事情,可是要用Ribbon
和Hystrix
自帶的註解必需要引入相應的jar包才能夠,
Feign還提供了HTTP請求
的模板,經過編寫簡單的接口和註解,就能夠定義好HTTP請求的參數、格式、地址等信息github
添加依賴web
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
複製代碼
開啓Feignspring
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
複製代碼
建立接口(feign提供的http請求模板) 經過@FeignClient("服務名")
,來指定調用哪一個服務restful
@FeignClient("eureka-provider")
public interface HomeClient {
@GetMapping("/") //服務提供者」/「訪問的方法
String consumer();
}
複製代碼
消費方法架構
//不解釋了吧
@RestController
public class ConsumerController {
@Autowired
private HomeClient homeClient;
@GetMapping(value = "/hello")
public String hello() {
return homeClient.consumer();
}
}
複製代碼
消費配置app
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: feign-consumer
server:
port: 9000
複製代碼
在github
上有關於Spring Cloud
完整的部署。
其它相關文章
Spring cloud(1)-簡介以及選擇
Spring cloud(2)-服務發現(Eureka,Consul)
Spring cloud(3)-負載均衡(Feign,Ribbon)
Spring cloud(4)-熔斷(Hystrix)
Spring cloud(5)-路由網關(Zuul)
Spring cloud(6)-配置管理及刷新(Config,Bus)
最後,給個 star 吧~
我的博客~
簡書~負載均衡