SpringCloud微服務呼叫方式之Ribbon和Feign方式
阿新 • • 發佈:2018-12-19
微服務呼叫方式之Ribbon的用法
- 匯入Ribbon的依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
- 使用註解的方式配置RestTemplate
@Configuration public class MyConfigurer { @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }
- 在需要呼叫其他服務介面的地方使用@Autowired註解直接注入RestTemplate 類 在呼叫restTemplate.getForObject(url, Object.class)方法 url:是的介面的地址(http://product-service(這裡是每個微服務在向註冊中心註冊的時候給自己起的名字,在配置檔案中的是spring.application.name: product-service的屬性值)/a/b(這裡是介面的具體地址))
package net.xdclass.order_service.service.impl; import net.xdclass.order_service.domain.ProductOrder; import net.xdclass.order_service.service.ProductOrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import sun.net.www.URLConnection; import sun.net.www.http.HttpClient; import java.util.Date; import java.util.UUID; @Service public class ProductOrderServiceImpl implements ProductOrderService { @Autowired private RestTemplate restTemplate; @Override public ProductOrder save(int productId) { Object obj = restTemplate.getForObject("http://product-service/api/find?id=2", Object.class); System.out.println(obj); return null; } }
微服務呼叫方式之feign的用法
- 加入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 在啟動類上增加@EnableFeignClients註解
- 新增加一個介面 並類上方新增@FeignClient(name=“product-service(這裡是被呼叫方的服務名)”)
- 在新增的介面中寫,需要呼叫對應服務的,Controller層的方法。方法的引數和請求的方式、地址必須相同。 傳的引數是基礎型別時,每個引數前需要新增@RequestParam(“xx”) 註解,方法上新增 @GetMapping("/a/b/c") 註解。 傳的引數是物件型別時,要新增@RequestBody 註解,方法上新增@PostMapping("/a/b/c") 註解
@FeignClient("product-service")
public interface ProductClient{
@PostMapping(value = "/updateProduct")
int update(@RequestBody Entity entity);
@GetMapping(value = "/deleteProduct")
int findById(@RequestParam("id") int id);
}
- 在需要呼叫其他服務介面的地方使用@Autowired註解直接注入新增的介面類,然後呼叫介面中對應的方法。返回的是json字串。
package net.xdclass.order_service.service.impl;
import net.xdclass.order_service.domain.ProductOrder;
import net.xdclass.order_service.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import sun.net.www.URLConnection;
import sun.net.www.http.HttpClient;
import java.util.Date;
import java.util.UUID;
@Service
public class ProductOrderServiceImpl implements ProductOrderService {
@Autowired
private ProductClient productClient;
@Override
public ProductOrder save(int productId) {
String response = productClient.findById(productId);
System.out.println(response );
return null;
}
}