RPC,RestTemplate,Feign概念


RPC,RestTemplate,Feign概念

RPC:

遠程服務調用,凡是像本地接口一樣調用遠程接口的方式,就是RPC。

RestTemplate:

RestTemplate是Spring提供的使用Restful遠程訪問Http的模板

使用

在使用之前,編寫配置類,注入Bean即可。

@Configuration
public class RestTemplateConfiguration {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

使用時:

@Autowired
private RestTemplate restTemplate;//注入依賴

public String getProduct(string productId) {
      String response=restTemplate.getForObject(“http://Product/getProduct/” + productId, String.class); //Product為應用名字
      return response;
}

Feign:(SpringCloud組件之一)

Feign默認封裝了Ribbon,是一個http請求調用的輕量級框架(客戶端),封裝了Http調用,簡化流程,更適合面向接口化。

Feign使用:

1.引入依賴

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>

2.@EnableFeignClients注解開啟Spring Cloud Feign的支持功能,以及@EnableDiscoveryClient注解。

3.在服務上使用@FeignClient指定服務名,然后再使用@RequestMapping的注解來綁定具體該服務提供的REST接口。

@FeignClient(value = "hello-service-provider")//服務名不區分大小寫
public interface HelloServiceFeign {

    @RequestMapping(value = "/demo/getHost", method = RequestMethod.GET)
    public String getHost(String name);

    @RequestMapping(value = "/demo/postPerson", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public Person postPerson(String name);
}

4.在另一個服務中,創建一個RestClientController來實現對Feign客戶端的調用。使用@Autowired直接注入上面定義的HelloServiceFeign實例,並在postPerson函數中調用這個綁定了hello-service服務接口的客戶端來向該服務發起/hello接口的調用。

5.服務都要注冊在注冊中心。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM