微服务之间的调用方式RestTemplate和Feign

一、RestTemplate简介与简单案例

1.1 简介

SpringRestTemplate是Spring 提供的用于访问 Rest 服务的客端, RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率,所以很多客户端比如Android或者第三方服务商都是使用RestTemplate 请求 restful服务.

1.2 简单案例

1.2.1 配置restTemplate

@Configuration

public class RestTemplateConfig {

 

    @Bean

    public RestTemplate restTemplate(ClientHttpRequestFactory factory){

        return new RestTemplate(factory);

    }

 

    @Bean

    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){

        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();

        factory.setReadTimeout(5000);//单位为ms

        factory.setConnectTimeout(5000);//单位为ms

        return factory;

    }

}

 

1.2.2 然后再需要访问的url类中注入restTemplate

@Autowired

private RestTemplate restTemplate;

 

1.2.3 在合适的地方请求

//get json数据

JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();

 

//post json数据

JSONObject postData = new JSONObject();

postData.put("data", "request for post");

JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();

 

二、Feign简介与简单案例

2.1 简介

Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。(简而言之:1.Feign 采用的是基于接口的注解;2.Feign 整合了ribbon,具有负载均衡的能力;3.整合了Hystrix,具有熔断的能力)

2.2 简单案例

2.2.1 pom文件引入jar

 <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-openfeign</artifactId>

 </dependency>

 

2.2.2 在程序的启动类加上@EnableFeignClients注解开启Feign的功能

@SpringBootApplication

@EnableEurekaClient

@EnableDiscoveryClient

@EnableFeignClients

public class ServiceFeignApplication {

 

    public static void main(String[] args) {

        SpringApplication.run( ServiceFeignApplication.class, args );

    }

}

 

2.2.3 定义Feign接口,通过@FeignClient(“服务名”)来指定调用那个服务.比如在代码中调用了service-hi服务的“/hi”接口,代码如下:

 

@FeignClient(value = "service-hi")

public interface SchedualServiceHi {

    @RequestMapping(value = "/hi",method = RequestMethod.GET)

String sayHiFromClientOne(@RequestParam(value = "name") String name);

}

 

2.2.3 在Web层的Controller,对外暴露一个"/hi"的API接口,通过上面定义的Feign客户端SchedualServiceHi 来消费服务。

@RestController

public class HiController {

    //编译器报错,无视。 因为这个Bean是在程序启动的时候注入的,编译器感知不到,所以报错。

    @Autowired

    SchedualServiceHi schedualServiceHi;

 

    @GetMapping(value = "/hi")

    public String sayHi(@RequestParam String name) {

        return schedualServiceHi.sayHiFromClientOne( name );

    }

}

 

三、RestTemplate与Feign的比较

3.1 相同点:都是通过REST接口调用服务的http接口,参数和结果默认都是通过jackson序列化和反序列化

3.2 不同点:1.FeignClient简化了请求的编写,且通过动态负载进行选择要使用哪个服务进行消费,而这一切都由Spring动态配置实现,我们不用关心这些,只管使用方法即可,就是简化了编写。RestTemplate还需要写上服务器IP这些信息等等,而FeignClient则不用。2.FeignClient可以方便统一管理服务,且服务调用简单易读;RestTemplate url不方便统一管理,且调用方式复杂.

服务间的相互调用我本人更加倾向于Feign调用方式

发布了33 篇原创文章 · 获赞 33 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_36090463/article/details/96314087