feign調用返回object類型轉換方式

feign調用返回object類型轉換

引入依賴

       <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
    /**
  * @Description: 將數據轉換到相應的容器
  * @param bean
  * @param clazz
  * @return
  * @throws
  * @author dlh
  * @date 2019/3/19 10:28
  */
 public static <T> T convertValue(Object bean, Class<T> clazz){
  try{
   ObjectMapper mapper = new ObjectMapper();
   return mapper.convertValue(bean, clazz);
  }catch(Exception e){
   logger.error("錯誤的轉換:BeanUtil.convertValue() --->" + e.getMessage());
   return null;
  }
 }

SpringCloud feign接口轉換服務

Feign是通過提供面向接口操作的方式來替代RestTemplate API的Rest操作。

使用Feign

Feign這種技術應用在服務消費端

修改pom.xml配置文件,加入Feign的依賴包

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

由於Fegin是將Rest的操作轉換成接口的形式,所以我們需要新建一個接口,並在接口上聲明@FeignClient註解

@FeignClient(value = "DEPT-PROVIDER",configuration = FeignClientConfig.class)
public interface DeptClientService {
    @RequestMapping(method= RequestMethod.GET,value="/dept/get/{id}")
    public Dept get(@PathVariable("id") long id) ;
    @RequestMapping(method=RequestMethod.GET,value="/dept/list")
    public List<Dept> list() ;
    @RequestMapping(method=RequestMethod.POST,value="/dept/add")
    public boolean add(Dept dept) ;
}
@Configuration
public class FeignClientConfig {
    @Bean
    public Logger.Level getFeignLoggerLevel() {
        return feign.Logger.Level.FULL ;
    }
    @Bean
    public BasicAuthRequestInterceptor getBasicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("admin", "admin");
    }
}

其中configuration = FeignClientConfig.class不是必須的,將configuration屬性去除仍然能work。

將之前的Rest操作的API,替換成面向DeptClientService接口的形式

@RestController
@RequestMapping("/consumer/dept")
public class ConsumerDeptController {
    @Autowired
    private DeptClientService deptClientService;
    @RequestMapping(value = "/get")
    public Dept get(long id) {
        return this.deptClientService.get(id);
    }
    @RequestMapping("/list")
    public List<Dept> list(){
        return this.deptClientService.list();
    }
    @RequestMapping("/add")
    public boolean add(Dept dept){
        return this.add(dept);
    }
/*
    public static final String DEPT_GET_URL = "http://DEPT-PROVIDER/dept/get/";
    public static final String DEPT_LIST_URL = "http://DEPT-PROVIDER/dept/list/";
    public static final String DEPT_ADD_URL = "http://DEPT-PROVIDER/dept/add";
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HttpHeaders httpHeaders;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @RequestMapping(value = "/get")
    public Dept get(long id) {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("DEPT-PROVIDER") ;
        System.out.println(
                "【*** ServiceInstance ***】host = " + serviceInstance.getHost()
                        + "、port = " + serviceInstance.getPort()
                        + "、serviceId = " + serviceInstance.getServiceId());
        //Dept dept = restTemplate.getForObject(DEPT_GET_URL + id, Dept.class);
        Dept dept = restTemplate.exchange(DEPT_GET_URL+id, HttpMethod.GET,new HttpEntity<Object>(this.httpHeaders),Dept.class).getBody();
        return dept;
    }
    @RequestMapping("/list")
    public List<Dept> list(){
        //List<Dept> deptList = restTemplate.getForObject(DEPT_LIST_URL, List.class);
        List<Dept> deptList = this.restTemplate.exchange(DEPT_LIST_URL,HttpMethod.GET,new HttpEntity<Object>(this.httpHeaders),List.class).getBody();
        return deptList;
    }
    @RequestMapping("/add")
    public boolean add(Dept dept){
        //Boolean flag = restTemplate.postForObject(DEPT_ADD_URL, dept, Boolean.class);
        Boolean flag = this.restTemplate.exchange(DEPT_ADD_URL,HttpMethod.POST,new HttpEntity<Object>(this.httpHeaders),Boolean.class).getBody();
        return flag;
    }*/
}

在啟動類中加入@EnableFeignClients註解

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"cn.zgc.service"})
public class FeignConsumer_80_StartSpringCloudApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignConsumer_80_StartSpringCloudApplication.class,args);
    }
}

Feign自帶瞭負責均衡特性,所以使用Feign之後可以不用使用Ribbon。

Feign的配置

Feign 最重要的功能就是將 Rest 服務的信息轉換為接口,但是在實際的使用之中也需要考慮到一些配置情況,例如:數據壓縮, Rest 的核心本質在於: JSON 數據傳輸( XML、文本),於是就必須思考一種情況,萬一用戶發送的數據很大呢? 所以這個時候可以考慮修改application.yml 配置文件對傳輸數據進行壓縮;

feign:
 compression:
 request:
 mime-types:  # 可以被壓縮的類型
 - text/xml
 - application/xml
 - application/json
 min-request-size: 2048 # 超過2048的字節進行壓縮

開啟Feign的日志(默認是不開啟的)

logging:
 level:
 cn.zgc.service: DEBUG

feign調用的時候返回參數不是期望的數據類型

今天碰到個坑,feign調用其他應用的時候反參並不是期望的類型;不知道這個在其他請求方式有沒有這個bug

解決的方法

是在feign調用的那裡指定Response<?>的泛型類,我這邊是碰到期望是返回Long類型,但是返回的是Integer類型,不知道是不是隱式轉換瞭,這裡記錄一下這個Bug

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: