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