当前位置: 代码网 > it编程>编程语言>Java > SpringCloud OpenFeign 自定义响应解码器的问题记录

SpringCloud OpenFeign 自定义响应解码器的问题记录

2024年06月17日 Java 我要评论
一、jsonresult 在openfeign 微服务调用的问题我们在使用 spring cloud 微服务的时候,通常将返回结果使用一个jsonresult 类进行封装,例如如下的格式:public

一、jsonresult 在 openfeign 微服务调用的问题

我们在使用 spring cloud 微服务的时候,通常将返回结果使用一个jsonresult 类进行封装,例如如下的格式:

public class jsonresult<t> {
    /* 响应码,200为成功   */
    private integer code;
    /* 失败时的具体失败信息   */
    private string message;
    /* 成功时的数据对象   */
    private t data;
}
 

而调用方在使用spring cloud openfeign定义的客户端调用远程服务时,由于远程微服务接口的返回值也是 jsonresult 对象,这样本地的接口也需要使用 jsonresult 进行接收,这增加了额外的result类重新拆开等工作。

有没有办法实现一些自定义的逻辑,比如将统一返回的result类重新拆开仅返回对应的业务对象,或者对特定的响应码进行处理等等?

二、自定义 openfeign 响应解码器

为了实现上述功能,我们就需要改造默认的decoder。spring cloud openfeign允许我们在定义一个feignclient 的时候,指定一个额外的配置类,比如:

@feignclient(
    name = "xxx-base", 
    path = "/api/base",
    configuration = customizedconfiguration.class /* 自定义配置类 */
)
public interface remoteuserservice {
    //..
}

我们可以在 customizedconfiguration 中定义一个自己的 decoder 来覆盖默认的配置。

spring cloud 对 feign的封装和默认配置可以查看官方文档

自定义的 decoder 需要实现feign.codec.decoder接口,也可以参考默认的decoder的实现逻辑(org.springframework.cloud.openfeign.support.responseentitydecoder),

下面的实现可以对统一返回值result类的解包,并对异常返回进行处理:

public class customizedconfiguration{
    @bean
    public decoder feigndecoder() {
        return new openfeignresultdecoder();
    }
}
public class openfeignresultdecoder implements decoder {
    @resource
    objectmapper objectmapper;
    @override
    public object decode(response response, type type) throws ioexception, decodeexception, feignexception {
        string resultjson = this.getresponsebody(response);
        try {
            javatype rawtype = objectmapper.gettypefactory().constructtype(type);
            javatype resulttype = objectmapper.gettypefactory().constructparametrictype(jsonresult.class, rawtype.getrawclass());
            jsonresult<?> jsonresult = objectmapper.readvalue(resultjson, resulttype );
            if (jsonresult.getcode() != httpstatus.ok.value()){
                throw new decodeexception(
                        response.status(),
                        jsonresult.getmessage(),
                        response.request());
            }
            return jsonresult.getdata();
        } catch (exception ex){
            throw new illegalargumentexception("对象转换失败: " + ex.getmessage());
        }
    }
    /* 
     * 将 response body 解析为 string 
     */ 
    private static string getresponsebody(response response) throws ioexception {
        response.body resbody = response.body();
        if (objects.isnull(resbody)){
            throw new decodeexception(
                    response.status(),
                    "返回体为空",
                    response.request());
        }
        string jsonstr;
        char[] buffer = new char[1024*4];
        int len;
        try (
                reader reader = resbody.asreader(standardcharsets.utf_8);
                stringwriter strwriter = new stringwriter()
        ){
            while ((len = reader.read(buffer)) != -1){
                strwriter.write(buffer, 0, len);
            }
            jsonstr= strwriter.tostring();
        }
        return jsonstr;
    }
}

实现了decoder之后,只需要将其配置到customizedconfiguration中即可。

三、为 feignclient 注册全局配置

注意如果customizedconfiguration添加了@configuration的注解,则会成为feign client构建的默认配置,这样就不需要在每个@feignclient注解中都去指定配置类了:

@configuration
public class openfeignconfig {
    @bean
    public decoder feigndecoder() {
        return new openfeignresultdecoder();
    }
}
@feignclient(
    name = "xxx-base",
    path = "/api/base"
)
public interface remoteuserservice {
    //..
}

四、使用 openfeign 远程服务示例

添加了自定义的decoder之后,如果一个远程接口的定义是这样的:

@feignclient(
    name = "xxx-base",
    path = "/api/base"
)
public interface remoteuserservice {
   @getmapping(value = "/user/detail/{userid}")
   public user getuserdetailbyid(@pathvariable integer userid)
}
// ...
@resource
remouteuserservice userservice
public void demouserservice(int userid){
    user user = userservice.getuserdetailbyid(userid);
    // ....
} 
 

到此这篇关于springcloud openfeign 自定义响应解码器的文章就介绍到这了,更多相关springcloud openfeign解码器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com