Idea+maven+spring-cloud项目搭建系列--9整合OpenFeign

前言:
本文是建立在已整合nacos 的基础上进行的扩展,如需要整合Nacos 可以参考:
https://blog.csdn.net/l123lgx/article/details/121624988

1 openFeign 介绍:
用于服务之间的通信;
Feign是一个声明式的伪RPC(Feign英文意思为“假装,伪装,变形”)的REST客户端,它用了基于接口的注解方式,可以以Java接口注解的方式调用Http请求,从而将请求模块化。

2 openFeign 使用:

2.1 spring-cloud 使用openFeign:
2.1.1 引入jar:

		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
 		 <!-- 使用okhttp 进行通信-->
     	<dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-okhttp</artifactId>
        </dependency>

2.1.2 启动类启用openFeign:

@EnableFeignClients(“org.lgx.bluegrass”)

在这里插入图片描述
2.1.3 在spring-cloud 项目下定义其它服务feign接口:
EsFeignService.java

package org.lgx.bluegrass.api.service;

import org.lgx.bluegrass.api.service.impl.EsFeignServiceFallBack;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * feign 接口
 * name :服务名称
 * fallback:接口调用失败处理类
 * @Description TODO
 * @Date 2022/1/6 16:43
 * @Author lgx
 * @Version 1.0
 */
@FeignClient(name = "bluegrass-es", fallback = EsFeignServiceFallBack.class)
public interface EsFeignService {
    @GetMapping(value = "/test/es/feign")
    String testFeign(@RequestParam("wd") String wd);
}

EsFeignServiceFallBack .java

package org.lgx.bluegrass.api.service.impl;

import org.lgx.bluegrass.api.service.EsFeignService;

/**
 * @Description TODO
 * @Date 2022/1/6 16:45
 * @Author lgx
 * @Version 1.0
 */
public class EsFeignServiceFallBack implements EsFeignService {
    @Override
    public String testFeign(String wd) {
        return null;
    }
}

2.1.4 调用远程服务定义feign接口:
SyncFeignService.java

package org.lgx.bluegrass.api.service;

import org.lgx.bluegrass.api.service.impl.SyncFeignServiceFallBack;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 远程服务接口调用
 * name:服务名称 可以省略
 * url: 远程服务url
 * fallback: 调用失败处理类
 * @Description TODO
 * @Date 2022/1/6 16:54
 * @Author lgx
 * @Version 1.0
 */
@FeignClient(name = "applicationname",url = "http://www.baidu.com",fallback = SyncFeignServiceFallBack.class)
public interface SyncFeignService {
    @GetMapping("/s")
    String search(@RequestParam("wd") String wd);
}

SyncFeignServiceFallBack.java

package org.lgx.bluegrass.api.service.impl;

import org.lgx.bluegrass.api.service.SyncFeignService;

/**
 * @Description TODO
 * @Date 2022/1/6 16:54
 * @Author lgx
 * @Version 1.0
 */
public class SyncFeignServiceFallBack implements SyncFeignService {
    @Override
    public String search(String wd) {
        return null;
    }
}

2.1.5 nacos yml文件配置:

feign:
  # 开启压缩
  compression:
    request:
      enabled: true
    response:
      enabled: true
  # 使用okhttp 通信
  okhttp:
    enabled: true

2.1.6 测试:

package org.lgx.bluegrass.bluegrasscoree.controller.feign;

import org.lgx.bluegrass.api.service.EsFeignService;
import org.lgx.bluegrass.api.service.SyncFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotEmpty;

/**
 * @Description TODO
 * @Date 2022/1/6 16:59
 * @Author lgx
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/feign/")
public class TestFeignController {
    @Autowired
    private EsFeignService esFeignService;
    @Autowired
    private SyncFeignService syncFeignService;

    @GetMapping("/testes")
    public String testEs(@RequestParam("wd") @NotEmpty String wd) {
        return esFeignService.testFeign(wd);
    }
    @GetMapping("/testsync")
    public String testSync(@RequestParam("wd") @NotEmpty String wd) {
        return syncFeignService.search(wd);
    }
}

3 扩展:
3.1 通过拦截feign 请求解决,请求header 丢失问题:

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.lgx.bluegrass.api.constant.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Description
 * @Date 2021/4/16 15:39
 * @Author lgx
 * @Version 1.0
 */
@Configuration
public class FeignConfiguration implements RequestInterceptor {
    private Logger logger = LoggerFactory.getLogger(FeignConfiguration.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
          // 获取之前的header 并放入新的header中
        if (attributes != null) {
            String authorization = attributes.getRequest().getHeader(Constant.X_AUTHORIZATION);
            if (null != authorization) {
                requestTemplate.header(Constant.X_AUTHORIZATION, authorization);
            }
            String dbName = attributes.getRequest().getHeader(Constant.dbName);
            if (null != dbName) {
                requestTemplate.header(Constant.dbName, dbName);
            }
            String userDb = attributes.getRequest().getHeader(Constant.userDb);
            if (null != userDb) {
                requestTemplate.header(Constant.userDb, userDb);
            }
        }
    }
}

3.2 通过请求api 增加@header:

@FeignClient(name = "dynamic", url = "http://localhost:8010", fallback = SyncFeignDynamicServiceFallBack.class)
public interface SyncFeignDynamicService {
    @RequestMapping("/user/getUserById")
    Object getUserById(@RequestParam("userId") Integer userId,@RequestHeader("userDb") String userDb) ;
}

注意:两种方法同时使用,最终生效的为@header

参考:
spring-cloud Feign 使用;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值