[TOC]
## Https vs RPC
* Dubbo(RPC框架)
* Spring Cloud
## SpringCloud中服务间两种restful调用方式
需要开启Eureka,并且把order和product两个服务注册进来
![](https://img.kancloud.cn/97/a1/97a14219424e5142745758581967e38d_2266x878.png)
### RestTemplate
#### server端
```
package com.cfun.product.Controller;
........
@RestController
public class ServerController {
@GetMapping("/msg")
public String msg(){
return "this is msg server";
}
}
```
#### client调用
```
package com.cfun.order.controller;
.......
@RestController
@Slf4j
public class ClientController {
@Autowired
private LoadBalancerClient loadBalancerClient;
@Autowired
private RestTemplate restTemplate;
@GetMapping("/getProductMsg")
public String getProductMsg() {
//1.使用restTemplate
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:8081/msg", String.class);
//2.第二种方式
RestTemplate restTemplate = new RestTemplate();
ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
String url=String.format("http://%s:%s",serviceInstance.getHost(),serviceInstance.getPort());
String response = restTemplate.getForObject("http://localhost:8081/msg", String.class);
//3.第三种方式.利用注解
String response =restTemplate.getForObject("http://PRODUCT/msg",String.class);
log.info("response={}",response);
return response;
}
}
```
#### RestTemplateConfig类
~~~
package com.cfun.order.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
~~~
### Feign
声明式REST客户端(伪RPC)
采用了基于接口的注解.
#### 添加依赖
```
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
```
#### 主类添加注解
~~~
@EnableFeignClients
~~~
#### 添加feign接口类
~~~
package com.cfun.order.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "Product")
public interface ProductClient {
@GetMapping("/msg")
String productMSg();
}
~~~
#### 使用
~~~
package com.cfun.order.controller;
import com.cfun.order.client.ProductClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@Slf4j
public class ClientFeginController {
@Autowired
private ProductClient productClient;
@GetMapping("/getProductMsg")
public String getProductMsg() {
String response =productClient.productMSg();
log.info("response={}",response);
return response;
}
}
~~~