openfeign 笔记

参考资料

Spring Cloud OpenFeign 中文文档

阿好程序 springbot 专栏
如何在Spring Boot中使用OpenFeign,这一篇足够了。
OpenFeign修改默认通讯协议Https
OpenFeign默认通讯方式修改成OkHttp,包含FeignConfigruation自定义、OkHttp客户端自定义详细配置介绍

基本使用

接口准备

controller

package com.laolang.jx.module.system.dict.controller;

import com.laolang.jx.framework.common.domain.R;
import com.laolang.jx.module.system.dict.logic.SysDictLogic;
import com.laolang.jx.module.system.dict.req.SysDictTypeListReq;
import com.laolang.jx.module.system.dict.rsp.SysDictTypeListRsp;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RequestMapping("admin/system/dict")
@RestController
public class SydDictController {

    private final SysDictLogic sysDictLogic;

    @GetMapping("getMethod")
    public R<SysDictTypeListRsp> getMethod() {
        return R.ok(sysDictLogic.getMethod());
    }

    @GetMapping("getMethodWithParam")
    public R<SysDictTypeListRsp> getMethodWithParam(@RequestParam(value = "id") Long id,
                                                    @RequestParam(value = "name", defaultValue = "laolang") String name) {
        return R.ok(sysDictLogic.getMethodWithParam(id, name));
    }

    @PostMapping("postMethod")
    public R<SysDictTypeListRsp> postMethod() {
        return R.ok(sysDictLogic.postMethod());
    }

    @PostMapping("postMethodWithFormData")
    public R<SysDictTypeListRsp> postMethodWithFormData(SysDictTypeListReq req) {
        return R.ok(sysDictLogic.postMethodWithFormData(req));
    }

    @PostMapping("postMethodWithRequestBody")
    public R<SysDictTypeListRsp> postMethodWithRequestBody(@RequestBody SysDictTypeListReq req) {
        return R.ok(sysDictLogic.postMethodWithRequestBody(req));
    }
}

logic

package com.laolang.jx.module.system.dict.logic;

import com.laolang.jx.framework.common.util.JsonUtil;
import com.laolang.jx.module.system.dict.req.SysDictTypeListReq;
import com.laolang.jx.module.system.dict.rsp.SysDictTypeListRsp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@RequiredArgsConstructor
@Service
public class SysDictLogic {

    public SysDictTypeListRsp getMethod() {
        log.info("getMethod");
        return buildRsp();
    }

    public SysDictTypeListRsp getMethodWithParam(Long id, String name) {
        log.info("getMethodWithParam");
        log.info("id:{}, name:{}", id, name);
        return buildRsp();
    }

    public SysDictTypeListRsp postMethod() {
        log.info("postMethod");
        return buildRsp();
    }

    public SysDictTypeListRsp postMethodWithFormData(SysDictTypeListReq req) {
        log.info("postMethodWithFormData. req:{}", JsonUtil.toJson(req));
        return buildRsp();
    }

    public SysDictTypeListRsp postMethodWithRequestBody(SysDictTypeListReq req) {
        log.info("postMethodWithRequestBody. req:{}", JsonUtil.toJson(req));
        return buildRsp();
    }

    private SysDictTypeListRsp buildRsp() {
        SysDictTypeListRsp rsp = new SysDictTypeListRsp();
        rsp.setId(1L);
        rsp.setName("性别");
        rsp.setType("gender");
        rsp.setTypeDesc("性别");
        rsp.setGroupCode("system");
        return rsp;
    }
}

jackson 配置

package com.laolang.jx.config.jackson;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JxJacksonAutoConfiguration {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {
        return builder -> {
            /* 数字格式化 */
            // BigDecimal 格式化
            builder.serializerByType(BigDecimal.class, new JsonSerializer<BigDecimal>() {
                @Override
                public void serialize(BigDecimal value, JsonGenerator gen,
                                      SerializerProvider serializers)
                        throws IOException {
                    DecimalFormat format = new DecimalFormat("0.00");
                    gen.writeString(format.format(value));
                }
            });
            // Long 格式化
            builder.serializerByType(Long.class, ToStringSerializer.instance);
            builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
            builder.serializerByType(long.class, ToStringSerializer.instance);

            /* 时间格式化 */
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(
                    DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
            builder.serializerByType(LocalDate.class,
                    new LocalDateSerializer(
                            DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
            builder.serializerByType(LocalTime.class,
                    new LocalTimeSerializer(
                            DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(
                    DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
            builder.deserializerByType(LocalDate.class,
                    new LocalDateDeserializer(
                            DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
            builder.deserializerByType(LocalTime.class,
                    new LocalTimeDeserializer(
                            DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
        };
    }
}

R

package com.laolang.jx.common.domain;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.laolang.jx.common.consts.DefaultStatusCode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import lombok.Data;
import lombok.experimental.Accessors;
import org.slf4j.MDC;

@Accessors(chain = true)
@Data
public class R<T> {

    /**
     * 接口请求结果的业务状态吗.
     */
    private String code;

    /**
     * 判断接口请求是否成功的唯一标识.
     */
    private Boolean success;

    /**
     * 提示信息.
     */
    private String msg;

    /**
     * 数据体.
     */
    private T body;

    /**
     * 扩充字段,正常情况下此字段为空,当此字段有值时,意味着当前接口结构不稳定,以后会修改,即保持 extra 为空.
     */
    private Map<String, Object> extra;

    /**
     * traceId
     */
    private String tid;

    /**
     * 接口返回时间
     */
    private LocalDateTime time;

    public static <T> R<T> build(String code, boolean success, String msg, T body) {
        R<T> ajax = new R<>();
        ajax.setCode(code);
        ajax.setSuccess(success);
        ajax.setMsg(msg);
        ajax.setBody(body);
        ajax.setExtra(null);
        ajax.setTid(getTraceId());
        ajax.time = LocalDateTime.now();

        return ajax;
    }

    private static String getTraceId() {
        String tl = MDC.get("tl");
        List<String> split = StrUtil.split(tl, ":");
        if (CollUtil.isEmpty(split) || split.size() < 2) {
            return "";
        }
        String tid = StrUtil.replace(split.get(1), "<", "");
        tid = StrUtil.replace(tid, ">", "");
        return tid;
    }

    public static <T> R<T> ok() {
        return ok(DefaultStatusCode.OK.getCode(), DefaultStatusCode.OK.getMsg());
    }

    public static <T> R<T> ok(String code, String msg) {
        return ok(code, msg, null);
    }

    public static <T> R<T> ok(String code, String msg, T body) {
        return build(code, true, msg, body);
    }

    public static <T> R<T> ok(T body) {
        return build(DefaultStatusCode.OK.getCode(), true, DefaultStatusCode.OK.getMsg(), body);
    }

    public static <T> R<T> failed() {
        return failed(DefaultStatusCode.FAILED.getMsg());
    }

    public static <T> R<T> failed(String msg) {
        return build(DefaultStatusCode.FAILED.getCode(), false, msg, null);
    }

    public static <T> R<T> error() {
        return error(DefaultStatusCode.ERROR.getMsg());
    }

    public static <T> R<T> error(String msg) {
        return error(DefaultStatusCode.ERROR.getCode(), msg);
    }

    public static <T> R<T> error(String code, String msg) {
        return build(code, false, msg, null);
    }

    public static <T> R<T> notFound() {
        return notFound(DefaultStatusCode.NOT_FOUND.getMsg());
    }

    public static <T> R<T> notFound(String msg) {
        return build(DefaultStatusCode.NOT_FOUND.getCode(), false, msg, null);
    }

    public static <T> R<T> unauthorized() {
        return build(DefaultStatusCode.UNAUTHORIZED.getCode(), false, DefaultStatusCode.UNAUTHORIZED.getMsg(), null);
    }
}

bizcode

package com.laolang.jx.common.consts;

public interface BizCode {

    /**
     * 业务异常状态码.
     */
    String getCode();

    /**
     * 业务异常描述.
     */
    String getMsg();
}

default code

package com.laolang.jx.common.consts;

public enum DefaultStatusCode implements BizCode {
    /**
     * 业务操作成功.
     */
    OK("200", "操作成功"),
    /**
     * 业务操作失败.
     */
    FAILED("1", "操作失败"),
    /**
     * 无权访问.
     */
    UNAUTHORIZED("401", "无权访问"),
    /**
     * 请求地址不存在.
     */
    NOT_FOUND("404", "请求地址不存在"),
    /**
     * 服务器内部错误.
     */
    ERROR("500", "服务器内部错误");

    /**
     * 业务状态码.
     */
    private final String code;

    /**
     * 提示信息.
     */
    private final String msg;

    DefaultStatusCode(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    @Override
    public String getCode() {
        return code;
    }

    @Override
    public String getMsg() {
        return msg;
    }
}

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.laolang.jx</groupId>
    <artifactId>jx-boot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

        <maven-resources-plugin.version>2.7</maven-resources-plugin.version>
        <maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version>

        <springboot.version>2.7.18</springboot.version>

        <tlog.version>1.5.0</tlog.version>

        <!-- tool -->
        <hutool.version>5.8.11</hutool.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${springboot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- web 相关 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- log4j2 日志 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <!-- TLog -->
        <dependency>
            <groupId>com.yomahub</groupId>
            <artifactId>tlog-web-spring-boot-starter</artifactId>
            <version>${tlog.version}</version>
        </dependency>

        <!-- tool -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>${hutool.version}</version>
        </dependency>


    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <resources>
            <resource>
                <directory>src/main/resources/</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>${maven-resources-plugin.version}</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${springboot.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>public</id>
            <name>aliyun nexus</name>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>public</id>
            <name>aliyun nexus</name>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>


</project>

启动类

package com.laolang.jx;


import com.yomahub.tlog.core.enhance.bytes.AspectLogEnhance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@Slf4j
@SpringBootApplication
public class JxApplication {
    static {
        AspectLogEnhance.enhance();
    }

    public static void main(String[] args) {
        SpringApplication.run(JxApplication.class, args);
        log.info("jx is running...");
    }
}

基本使用

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.laolang.jx</groupId>
    <artifactId>openfeign-study</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

        <maven-resources-plugin.version>2.7</maven-resources-plugin.version>
        <maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version>

        <springboot.version>2.7.18</springboot.version>
        <spring-cloud.version>2021.0.7</spring-cloud.version>

        <tlog.version>1.5.0</tlog.version>

        <!-- tool -->
        <hutool.version>5.8.11</hutool.version>
        <vavr.version>0.10.4</vavr.version>
        <mapstruct.version>1.4.2.Final</mapstruct.version>
        <guava.version>23.0</guava.version>

        <!-- test -->
        <testng.version>6.14.3</testng.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${springboot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- spring cloud 依赖 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- web 相关 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- 远程服务调用 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>


        <!-- log4j2 日志 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <!-- tool -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>${hutool.version}</version>
        </dependency>
        <dependency>
            <groupId>io.vavr</groupId>
            <artifactId>vavr</artifactId>
            <version>${vavr.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct</artifactId>
            <version>${mapstruct.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>${mapstruct.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-processor</artifactId>
            <version>${mapstruct.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${guava.version}</version>
        </dependency>

        <!-- 测试相关 -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <resources>
            <resource>
                <directory>src/main/resources/</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>${maven-resources-plugin.version}</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${springboot.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>public</id>
            <name>aliyun nexus</name>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>public</id>
            <name>aliyun nexus</name>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

启动类

package com.laolang.jx;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@Slf4j
@EnableFeignClients(basePackages = {"com.laolang.jx.remote"})
@SpringBootApplication
public class OpenfeignStudyApplication {
    public static void main(String[] args) {
        SpringApplication.run(OpenfeignStudyApplication.class, args);
        log.info("OpenfeignStudyApplication is running...");
    }
}

feign 接口

package com.laolang.jx.remote;

import com.laolang.jx.common.domain.R;
import com.laolang.jx.req.SysDictTypeListReq;
import com.laolang.jx.rsp.SysDictTypeListRsp;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient( name = "sysDict", url = "http://localhost:8092/admin/system/dict")
public interface SysDictRemote {

    @GetMapping("getMethod")
    R<SysDictTypeListRsp> getMethod();

    @GetMapping("getMethodWithParam")
    R<SysDictTypeListRsp> getMethodWithParam(@RequestParam(value = "id") Long id,
                                             @RequestParam(value = "name", defaultValue = "laolang") String name);

    @PostMapping("postMethod")
    R<SysDictTypeListRsp> postMethod();

    @PostMapping("postMethodWithFormData")
    R<SysDictTypeListRsp> postMethodWithFormData(SysDictTypeListReq req);

    @PostMapping("postMethodWithRequestBody")
    R<SysDictTypeListRsp> postMethodWithRequestBody(@RequestBody SysDictTypeListReq req);
}

测试

package com.laolang.jx;

import cn.hutool.json.JSONUtil;
import com.laolang.jx.common.domain.R;
import com.laolang.jx.remote.SysDictRemote;
import com.laolang.jx.req.SysDictTypeListReq;
import com.laolang.jx.rsp.SysDictTypeListRsp;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.testng.annotations.Test;

@Slf4j
@SpringBootTest(classes = OpenfeignStudyApplication.class)
public class OpenfeignSimpleTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private SysDictRemote sysDictRemote;


    /**
     * 无参 get 请求
     */
    @Test
    public void testGetMethod() {
        R<SysDictTypeListRsp> r = sysDictRemote.getMethod();
        log.info(JSONUtil.toJsonStr(r));
    }

    /**
     * get 请求带参数
     */
    @Test
    public void testGetMethodWithParam() {
        R<SysDictTypeListRsp> r = sysDictRemote.getMethodWithParam(1L, "潼关路边的一只野鬼");
        log.info(JSONUtil.toJsonStr(r));
    }

    /**
     * 无参 post 请求
     */
    @Test
    public void testPostMethod() {
        R<SysDictTypeListRsp> r = sysDictRemote.postMethod();
        log.info(JSONUtil.toJsonStr(r));
    }

    /**
     * post form 表单请求
     */
    @Test
    public void testPostMethodWithFormData() {
        SysDictTypeListReq req = new SysDictTypeListReq();
        req.setName("gender");
        R<SysDictTypeListRsp> r = sysDictRemote.postMethodWithFormData(req);
        log.info(JSONUtil.toJsonStr(r));
    }

    /**
     * post json 请求
     */
    @Test
    public void testPostMethodWithRequestBody() throws IOException {
        SysDictTypeListReq req = new SysDictTypeListReq();
        req.setName("gender");
        R<SysDictTypeListRsp> r = sysDictRemote.postMethodWithRequestBody(req);
        log.info(JSONUtil.toJsonStr(r));
    }
}
posted @ 2024-09-30 08:26  潼关路边的一只野鬼  阅读(5)  评论(0编辑  收藏  举报