欢迎来到Vincentyw的博客

该来的终究会来,该走的也一定会离开。凡事都存在前因后果,因缘成熟了,果报便产生了,无法阻挡。
但是发生过了就会消失,有来就有走,一切都是过客,把握自己当下的因缘,承担起自己该承担的责任,做好眼前该做的事情,做的时候尽全力,过去便放下,放下即自在。

openfeign应用汇总(三)

openfeign应用汇总(三)

1、自定义统一处理正确返回结果(实现Decoder)

import java.io.IOException;
import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;

public class FeignResultDecoder  implements Decoder{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Object decode(Response paramResponse, Type paramType) throws IOException{
        if(paramResponse.body() == null) {
            throw new DecodeException(paramResponse.status(), "没有返回数据", paramResponse.request());
        }
        try {
            String res = Util.toString(paramResponse.body().asReader(Util.UTF_8));
            logger.info("result :"+res);
            return res;
        } catch (Exception e) {
            throw  new IOException("无法解码返回报文",e);
        }
    }
}

2、自定义统一处理错误返回结果(实现ErrorDecoder)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kayak.exception.ErrorException;

import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.ErrorDecoder;

public class FeignErrorDecoder  implements ErrorDecoder{
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    String result = "远程调用出现异常"; 

    @Override
    public Exception decode(String paramString, Response paramResponse) {
        logger.info("erorStatus:"+paramResponse.status());
        if(paramResponse.body() == null) {
            throw new DecodeException(paramResponse.status(), "没有返回数据", paramResponse.request());
        }
        try {
            result = Util.toString(paramResponse.body().asReader(Util.UTF_8));
            logger.info("异常result:"+result);
            return new ErrorException(paramResponse.status()+"", result);
        } catch (Exception e) {
            return new ErrorException("999"+"", result);
        }
    }
}

3、使自定义解码器生效

@Configuration
public class FeignClientConfiguration{

    @Bean
    public Logger.Level feignLogLevel(){
        // 配置日志级别
        return Logger.Level.FULL;
    }

    @Bean
    public Decoder feignDefDecoder() {
        return new FeignResultDecoder();
    }

    @Bean
    public ErrorDecoder feignErrorDecoder() {
        return new FeignErrorDecoder();
    }

} 

4、Nacos配置加载并自动进行刷新

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import lombok.Data;

@RefreshScope ###更新nacos配置自动刷新
@Component
@Data
public class NacosConfig {

    @Value(value="${weixin.wechatMchId}")
    private  String  wechatMchId;
    
    @Value(value="${weixin.appid}")
    private  String  appid;
}

5、hystrix熔断机制,抛出自定义异常或者捕捉原异常

###方式一 实现feignClient接口 ###直接抛出自定义异常
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.kayak.common.base.entity.BaseRequest;
import com.kayak.integration.client.UserInfoFeignClient;
import com.kayak.message.domain.base.UserInfoRequest;
@Component
public class UserInfoFeignClientFallBack implements UserInfoFeignClient{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String getUserInfo(BaseRequest<UserInfoRequest> baserequest) {
        logger.info("远程调用出现异常");
        return "远程调用出现异常";
    }
}


###方式二 实现FallbackFactory接口 ###捕捉原定义异常信息
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.kayak.integration.client.WxSendFeignClient;
import com.kayak.message.domain.base.CouponsRequest;

import feign.hystrix.FallbackFactory;
@Component
public class WxSendFeignClientFallBack implements FallbackFactory<WxSendFeignClient>{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public WxSendFeignClient create(Throwable error) {

        return new WxSendFeignClient() {
            @Override
            public String queryCoupon(String openId, String coupon_id, String token, String appid) {
                String errStr = error.getMessage();
                logger.info("远程调用出现异常,error:"+errStr);
                return errStr;
            }
            @Override
            public String getCoupons(CouponsRequest couponsRequest, String openId, String token) {
                String errStr = error.getMessage();
                return errStr;            
            }
        };
    }
}

 

posted on 2023-08-07 21:50  VincentYew  阅读(36)  评论(0编辑  收藏  举报

导航