springcloud系列五 feign远程调用服务

时间:2023-03-09 10:00:16
springcloud系列五 feign远程调用服务

一:Feign简介

Feign 是一种声明式、模板化的 HTTP 客户端,在 Spring Cloud 中使用 Feign,可以做到使用 HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是个 HTTP 请求。

Feign 的灵感来源于 Retrofit、JAXRS-2.0 和 WebSocket,它使得 Java HTTP 客户端编写更方便,旨在通过最少的资源和代码来实现和 HTTP API 的连接。

二:Feign使用步骤

在客户端集成Feign即可

第一步:pom依赖

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

由于可能特别多的模块需要调用其他模块的项目,那么就需要进行统一依赖,减少重复依赖:

所以将这个依赖添加至父工程里面

springcloud系列五 feign远程调用服务

启动类添加注解开启远程调用:

package com.cxy;

import com.netflix.loadbalancer.BestAvailableRule;
import com.netflix.loadbalancer.IRule;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate; /***
* @ClassName: PersonApplication
* @Description:
* @Auther:
* @Date: 2019/1/2816:30
* @version : V1.0
*/
@SpringBootApplication
@EnableEurekaClient //开启注解,注册服务
@MapperScan("com.cxy")
@EnableFeignClients
public class UserApplication {
public static void main(String[] args) { SpringApplication.run(UserApplication.class,args);
}
@Bean
@LoadBalanced //使用负载均衡器Ribbon
public RestTemplate getRestTemplate(){
return new RestTemplate();
} /*@Bean
public IRule myRule(){
//return new RoundRobinRule();//轮询
// return new RetryRule();//重试
return new BestAvailableRule();
}*/
}
@EnableFeignClients,这个注解

远程调用方法首先需要写一个接口,可以当作是service:
package com.cxy.service;

import com.cxy.dataObject.PersonDo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Component
@FeignClient("cxy-person-service")
public interface IPersonService {
@RequestMapping("/person/{id}")
PersonDo getPersonDoById(@PathVariable("id") Integer id);
}

contrller调用

    @Autowired
private IPersonService personService;
  **/
@RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
public PersonDo selectPsersonById(@PathVariable Integer id){
PersonDo personDo =personService.getPersonDoById(id);
return personDo; }

启动访问:

springcloud系列五 feign远程调用服务

直接访问结果:

springcloud系列五 feign远程调用服务

此处已经成功了