springcloud==openfeign

单独使用

创建一个服务端

复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class UserServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }

    @RestController
    class UserController {

        @GetMapping("/users/{id}")
        public User getUser(@PathVariable String id) {
            // 模拟用户信息
            return new User(id, "User" + id);
        }
    }

    class User {
        private String id;
        private String name;

        // 构造函数、getters、setters
    }
}

创建一个客户端用openfeign去访问服务端

客户端的依赖

<dependency>

<groupId>io.github.openfeign</groupId>

<artifactId>feign-core</artifactId>

<version>13.1.0</version>

</dependency>

<dependency>

<groupId>io.github.openfeign</groupId>

<artifactId>feign-gson</artifactId>

<version>13.1.0</version>

</dependency>

复制代码
import feign.Feign;
import feign.gson.GsonDecoder;
import feign.Param;
import feign.RequestLine;

public class FeignDemo {

    interface UserClient {
        @RequestLine("GET /users/{id}")
        User getUserById(@Param("id") String id);
    }

    public static void main(String[] args) {
        UserClient userClient = Feign.builder()
                                     .decoder(new GsonDecoder())
                                     .target(UserClient.class, "http://localhost:8080");

        User user = userClient.getUserById("123");
        System.out.println(user.getName());
    }

    static class User {
        private String id;
        private String name;

        // getters 和 setters
    }
}

其中openfeign的作用:

复制代码
执行了几个关键步骤:

动态代理: Feign 使用了动态代理设计模式来创建 UserClient 接口的代理实例。这是一种结构型设计模式,允许在运行时创建一个实现了一组接口的对象。

构建请求模板: 对于接口中的每个方法,Feign 会构建一个请求模板,该模板包含了请求的方法、URL 和参数等信息。

反射: Feign 通过 Java 反射机制来解析接口上的注解,这样它就能了解如何构建 HTTP 请求和处理响应。

构建 HTTP 客户端: Feign 使用构建好的配置创建一个 HTTP 客户端,这个客户端用于发送请求。

请求拦截器: 如果配置了请求拦截器,Feign 会在发送请求之前处理这些拦截器,这常用于添加身份验证信息等。

装饰器模式: Feign 可以使用装饰器模式来包装 HTTP 客户端,添加额外的功能,如日志记录、重试机制等。

由于客户端是单纯用了openfeign,所以最终是建立一个HttpURLConnection,然后发出请求

相关推荐
a_157153249862 小时前
SpringCloud学习笔记-4
笔记·学习·spring cloud
eternal__day1 天前
Spring Cloud 多机部署与负载均衡实战详解
java·spring boot·后端·spring cloud·负载均衡
记得开心一点嘛2 天前
使用MinIO搭建自己的分布式文件存储
分布式·spring cloud·minio
LI JS@你猜啊2 天前
window安装docker
java·spring cloud·eureka
14L3 天前
互联网大厂Java面试:从Spring Cloud到Kafka的技术考察
spring boot·redis·spring cloud·kafka·jwt·oauth2·java面试
小马爱记录3 天前
sentinel规则持久化
java·spring cloud·sentinel
小马爱记录3 天前
Sentinel微服务保护
spring cloud·微服务·架构·sentinel
曼彻斯特的海边3 天前
RequestRateLimiterGatewayFilterFactory
spring cloud·gateway·限流
ghie90903 天前
SpringCloud-基于SpringAMQP实现消息队列
后端·spring cloud·ruby
要阿尔卑斯吗3 天前
Spring Cloud OpenFeign 实现动态服务名调用指南
spring cloud