Skip to content

Call Rest Api by Feign

🏷️ Spring Boot Feign

功能: 通过 Feign 调用远程 Api。

pom.xml

添加依赖 feign-jacksonfeign-slf4j

xml
<!-- Feign -->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-jackson</artifactId>
    <version>${feign.version}</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-slf4j</artifactId>
    <version>${feign.version}</version>
    <exclusions>
        <exclusion>
            <artifactId>feign-core</artifactId>
            <groupId>io.github.openfeign</groupId>
        </exclusion>
    </exclusions>
</dependency>

AresApi.java

定义 Api 接口。

java
import feign.Headers;
import feign.Param;
import feign.RequestLine;

import java.util.Map;

public interface AresApi {

    /**
     * 获取微信公众号 Access Token
     *
     * @param appid
     * @return
     */
    @RequestLine("GET /token?appid={appid}")
    AresResponse<AresAccessTokenData> getAccessToken(@Param("appid") String wAppid);
}

AresApiConfig.java

使用 Feign.builder() 创建 Api 的 Bean。

java
import feign.Feign;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AresApiConfig {

    @Bean
    public AresApi createAresApi(AresConfig aresConfig) {
        return Feign.builder()
                .encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder())
                .target(AresApi.class, String.format("http://%s/", aresConfig.getDomain()));
    }
}

AresServiceImpl.java

调用方法同调用普通的服务接口一样。

java
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AresServiceImpl extends AbstractAresService {

    @Autowired
    private AresApi aresApi;

    /**
     * 获取微信公众号访问令牌
     *
     * @param appId   微信公众号应用 ID
     * @return
     */
    @Override
    public AresAccessTokenData getAccessToken(String appId) {
        AresResponse<AresAccessTokenData> response = aresApi.getAccessToken(appId);
        log.info("response : {}", JSONUtil.toJsonStr(response));

        if (response != null && response.getCode() != null && response.getCode() == 200) {
            return response.getData();
        } else {
            log.error("获取 Access Token 失败");
            return null;
        }
    }
}