spring-cloud-feign及其应用

2022-07-30  本文已影响0人  轻舞凋零

feign提供的功能

java支持的接口调用方式

feign对各类http调用包进行了抽象,我们不必自己去调用http包,feign进行了封装

feign的使用

spring.application.name=eureka-client-front
server.port=7012

eureka.client.serviceUrl.defaultZone=http://tom:123456@localhost:6010/eureka/,http://tom:123456@localhost:6020/eureka/
eureka.instance.preferIpAddress=true
eureka.instance.instance-id=${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
eureka.client.healthcheck.enabled=true
eureka.instance.lease-expiration-duration-in-seconds=5
eureka.instance.lease-renewal-interval-in-seconds=15

eureka.instance.metadata-map.yuantiandi=tom

ribbon.eureka.enabled=true

logging.level.com.cxytiandi.feign_demo.remote.UserRemoteClient=DEBUG

feign.httpclient.enabled=false
feign.okhttp.enabled=true
feign.client.config.eureka-client-user.connect-timeout=1000
feign.client.config.eureka-client-user.readTimeout=1000




@FeignClient(value="eureka-client-user", configuration= FeignConfiguration.class)
public interface UserInfoClientApi {

    @GetMapping("/user/{uid}")
    public String info(@PathVariable long uid);
}


@Slf4j
public class FeignAuthInterceptor implements RequestInterceptor {

    public FeignAuthInterceptor() {

    }

    @Override
    public void apply(RequestTemplate template) {
        log.info("拦截器生效了");
    }
}
@Configuration
public class FeignConfiguration {
    /**
     * 日志级别
     *
     * @return
     */
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("tom", "123456");
    }

    @Bean
    public FeignAuthInterceptor feignBasicAuthRequestInterceptor() {
        return new FeignAuthInterceptor();
    }

}

直接使用openfeign

package cn.beckbi;

import feign.Param;
import feign.RequestLine;


public interface InfoApi {

    @RequestLine("GET /user/{uid}")
    String info(@Param(value = "uid") long uid);

}

@RestController
public class HiController {

    @GetMapping("/hi")
    public String hi() {
         InfoApi infoApi = HiController.getRestClient(InfoApi.class, "http://127.0.0.1:7010/");
         return infoApi.info(123456L);
    }

    public static <T> T getRestClient(Class<T> apiType, String url) {
        return Feign.builder().target(apiType, url);
    }

}

附录

实现的代码见:https://github.com/beckbikang/spring-cloud

上一篇下一篇

猜你喜欢

热点阅读