当前位置: 首页 > article >正文

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,然后发出请求


http://www.kler.cn/a/158191.html

相关文章:

  • 【Classic Chinese】
  • 【QT5】QT5安装
  • 阿里云效一键部署前后端
  • mysql中锁的具体使用
  • 【openssl】Window系统如何编译openssl
  • Mysql 行转列,把逗号分隔的字段拆分成多行
  • 04.里氏替换原则(Liskov Substitution Principle)
  • 三、C语言常见概念
  • 利用document.write阻塞js文件加载
  • React都有哪些hooks?
  • git常用命令小记
  • 数据结构——希尔排序(详解)
  • 在Vue3中使用缓存组件keep-alive vue3缓存组件
  • XXL-Job详解(三):任务开发
  • java--抽象类的常见应用场景:模板方法设计模式
  • PTA 7-230 美好日子
  • 【电路笔记】-电阻器额定功率
  • 降本提效!阿里提出大模型集成新方法
  • JS 实现一键复制文本内容
  • 面向注解编程—Spring 注解看这一篇就够了