【Spring实战】动手拥有自己的ai小站!使用Springboot整合Spring Cloud Gateway实现对接open ai并实现令牌记量和限制对话次数

简介: 【Spring实战】动手拥有自己的ai小站!使用Springboot整合Spring Cloud Gateway实现对接open ai并实现令牌记量和限制对话次数

在看这一篇之前  我是建议大家先去了解一下Springcloud Gateway的原理解读 就是我这篇文章《【云原生】Spring Cloud Gateway的底层原理与实践方法探究》


前端部分


这边建议直接套chatWeb的模板   前端的实现不是这里的重点   当然有兴趣的同学可以去翻一下源码   我把连接放这了哈GitHub - SuSuZeer/chatgpt-web-with-recharge: 使用vue3搭建的chatgpt聊天页面 在此基础上接入后端 使用Spring Cloud Gateway作为网关 增加了token计量检测 可以在此基础上建立一个充值系统


后端部分


准备工作


  1. 安装和配置Java开发环境
  2. 安装和配置Java开发环境
  3. 首先,确保你的计算机已经安装了Java开发工具包(JDK)。你可以从官方网站(https://www.oracle.com/java/technologies/javase-jdk15-downloads.html)下载并安装JDK。

安装完成后,设置环境变量,以便Java开发工具包可以在计算机上被访问。在Windows系统上,可以按照以下步骤进行设置:


  1. 打开控制面板并选择"系统和安全"。
  2. 点击"系统",然后选择"高级系统设置"。
  3. 在"高级"选项卡下,点击"环境变量"按钮。
  4. 在"系统变量"部分,点击"新建"按钮。
  5. 输入"JAVA_HOME"作为变量名,并将变量值设置为JDK安装目录的路径(例如:C:\Program Files\Java\jdk-15)。
  6. 点击"确定"保存设置。
  7. 在MacOS或Linux系统上,可以使用命令行设置环境变量。例如,在MacOS上,可以在终端中输入以下命令:
export JAVA_HOME=/usr/lib/jvm/java-15-openjdk-amd64
  1. 创建Spring Boot项目

接下来,我们将使用Spring Initializr创建一个新的Spring Boot项目。打开你的文本编辑器,创建一个新的Java项目,并按照以下步骤进行设置:

  1. 访问Spring Initializr网站(https://start.spring.io/)。
  2. 在页面上选择所需的项目配置,包括构建工具(Maven或Gradle)、Spring Boot版本和项目元数据。
  3. 在"Dependencies"部分,搜索并添加所需的依赖,如Spring Web、Spring Data JPA等。
  4. 点击"Generate"按钮,下载生成的项目压缩文件。
  5. 解压缩项目文件后,你就拥有一个基本的Spring Boot项目结构,可以开始进行开发。


  1. 导入所需的依赖

在项目的pom.xml文件中,你可以添加所需的依赖。例如,如果你需要使用Spring Web框架,可以添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 注册Open AI账号并获取API密钥

这里的话 最近注册比较 难 需要找好一点的魔法还要国外的接平台  

因为 有的节点 太多人用 他就会崩

当然了 相信很多人已经注册了账号了  那就按照官方的指示获取APIKey即可


Spring Cloud Gateway入门


  1. 了解API网关的概念和作用

API网关是一个中间层,用于在后端服务和客户端之间提供统一的访问接口。它扮演着流量控制、安全认证、请求转发和协议转换等角色,简化了微服务架构中的复杂性。API网关可以集中处理共享的功能,如身份验证、授权、请求转发和负载均衡,从而减轻了后端服务的负担。

  1. 使用Spring Cloud Gateway进行基本的路由配置
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  1. 实现请求转发和负载均衡   下文细讲此处

与Open AI对接


使用Spring Boot调用Open AI的API


添加Spring Cloud Gateway依赖


在项目的pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>com.openai</groupId>
    <artifactId>openai-java-sdk</artifactId>
    <version>1.0.0</version>
</dependency>

创建并配置OpenAiGatewayConfig类。

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
 
@Configuration
public class OpenAiGatewayConfig {
 
    private final OpenAiService openAiService;
 
    public OpenAiGatewayConfig(OpenAiService openAiService) {
        this.openAiService = openAiService;
    }
 
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("openai_chat", r -> r.path("/openai/chat")
                        .and()
                        .method(HttpMethod.POST)
                        .filters(f -> f.filter((exchange, chain) -> {
                            // 获取请求参数,例如用户输入的对话消息
                            String message = exchange.getRequest().getBody().toString();
                            // 调用OpenAI API的Chat接口进行对话
                            String response = openAiService.chat(message);
                            // 返回OpenAI API的响应给客户端
                            return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(response.getBytes())));
                        }))
                        .uri("http://api.openai.com/v1/chat/completions")
                )
                .build();
    }
}

创建了一个名为customRouteLocator的RouteLocator Bean,该Bean定义了一个路由规则,将请求路径为/openai/chat且HTTP方法为POST的请求转发到OpenAI API的Chat接口上。


创建OpenAiService类。


创建一个名为OpenAiService的服务类,用于与OpenAI API进行交互。示例代码如下:

import com.openai.OpenAiApi;
import com.openai.model.ChatCompletionRequest;
import com.openai.model.ChatCompletionResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
@Service
public class OpenAiService {
 
    @Value("${openai.api.key}")
    private String apiKey;
 
    public String chat(String message) {
        OpenAiApi openAiApi = new OpenAiApi(apiKey);
        ChatCompletionRequest request = new ChatCompletionRequest();
        // 设置Chat接口所需的参数
        // ...
        ChatCompletionResponse response = openAiApi.chatCompletion(request);
        // 处理Chat接口的响应,返回对话结果
        // ...
        return response.getText();
    }
}

使用OpenAI Java SDK来与OpenAI API进行交互。在chat方法中,根据OpenAI API文档中Chat接口的要求,设置请求参数并调用Chat接口,然后处理响应并返回对话结果。


配置应用程序属性。


在application.properties(或application.yml)文件中,配置OpenAI API的密钥:openai.api.key=YOUR_OPENAI_API_KEY


启用Spring Cloud Gateway


在Spring Boot应用程序的入口类(例如BlogApplication.java)上添加@EnableGateway注解,以启用Spring Cloud Gateway。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.config.GatewayAutoConfiguration;
import org.springframework.cloud.gateway.config.GatewayClassPathWarningAutoConfiguration;
import org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration;
 
@SpringBootApplication(exclude = {
        GatewayAutoConfiguration.class,
        GatewayClassPathWarningAutoConfiguration.class,
        GatewayReactiveLoadBalancerClientAutoConfiguration.class
})
@EnableGateway
public class BlogApplication {
    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

配置负载均衡


如果你希望实现负载均衡,可以在application.properties文件中添加以下配置:

spring.cloud.gateway.discovery.locator.enabled=true

这将启用Spring Cloud Gateway与服务发现组件(如Eureka、Consul等)集成,以实现负载均衡。


发送请求到Spring Cloud Gateway


现在,你可以将请求发送到Spring Cloud Gateway的路由上,然后它会将请求转发到OpenAI的API。


准备一个Spring Boot控制器,用于处理与OpenAI相关的请求:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
 
@RestController
public class OpenAIController {
 
    @Autowired
    private RestTemplate restTemplate;
 
    @PostMapping("/api/openai")
    public ResponseEntity<String> invokeOpenAI(@RequestBody String requestBody) {
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
 
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
 
        return restTemplate.exchange("http://localhost:8080/api/openai", HttpMethod.POST, requestEntity, String.class);
    }
}

在上面的代码中,我们使用RestTemplate来发送请求到Spring Cloud Gateway的路由。Spring Cloud Gateway会将请求转发到OpenAI的API。这样就实现了基本的对话了!


利用Spring Cloud Gateway实现令牌记量和限制对话次数


创建TokenLimiterFilter类


首先,创建一个名为TokenLimiterFilter.java的类,它将实现全局过滤器接口GlobalFilter和Ordered接口。

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
 
@Component
public class TokenLimiterFilter implements GlobalFilter, Ordered {
 
    private static final String API_KEY_HEADER = "X-API-Key";
    private static final int MAX_REQUESTS_PER_MINUTE = 100;
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String apiKey = request.getHeaders().getFirst(API_KEY_HEADER);
 
        // 检查 API Key 是否有效
        if (isValidApiKey(apiKey)) {
            // 检查对话次数是否超过限制
            if (isWithinRateLimit(apiKey)) {
                // 更新对话次数计数器
                updateRequestCount(apiKey);
                return chain.filter(exchange);
            } else {
                // 对话次数超过限制,返回错误响应
                exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
                return exchange.getResponse().setComplete();
            }
        } else {
            // 无效的 API Key,返回错误响应
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }
 
    private boolean isValidApiKey(String apiKey) {
        // 根据实际逻辑检查 API Key 的有效性
        // 返回 true 表示 API Key 有效,返回 false 表示无效
        return /* 根据实际逻辑进行判断 */;
    }
 
    private boolean isWithinRateLimit(String apiKey) {
        // 根据实际逻辑检查对话次数是否超过限制
        // 返回 true 表示对话次数未超过限制,返回 false 表示超过限制
        int requestCount = /* 根据实际逻辑获取对话次数 */;
        return requestCount < MAX_REQUESTS_PER_MINUTE;
    }
 
    private void updateRequestCount(String apiKey) {
        // 根据实际逻辑更新对话次数计数器
    }
 
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}

在上面的代码中,我们实现了filter方法,在该方法中执行了以下操作:

  • 获取请求中的API Key。
  • 检查API Key是否有效。
  • 检查对话次数是否超过限制。
  • 根据结果返回相应的响应给客户端。


启用TokenLimiterFilter


在Spring Boot应用程序的入口类(例如BlogApplication.java)上添加@EnableGateway注解,以启用Spring Cloud Gateway,并通过@ComponentScan注解扫描并启用TokenLimiterFilter。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.config.GatewayAutoConfiguration;
import org.springframework.cloud.gateway.config.GatewayClassPathWarningAutoConfiguration;
import org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RestController;
 
@SpringBootApplication(exclude = {
        GatewayAutoConfiguration.class,
        GatewayClassPathWarningAutoConfiguration.class,
        GatewayReactiveLoadBalancerClientAutoConfiguration.class
})
@EnableGateway
@ComponentScan(basePackages = "com.example.gateway")
@RestController
public class BlogApplication {
    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
}

现在,当请求经过Spring Cloud Gateway时,它将拦截并使用TokenLimiterFilter进行处理。在TokenLimiterFilter中,就可以根据实际需求实现令牌记量和对话次数限制的逻辑!

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
相关文章
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
1691 2
Spring Boot 3.x 微服务架构实战指南
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
1039 2
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
1645 0
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
1615 0
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
695 0
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
1338 0
|
Java 测试技术 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
562 0
|
JavaScript Java Maven
【SpringBoot(二)】带你认识Yaml配置文件类型、SpringMVC的资源访问路径 和 静态资源配置的原理!
SpringBoot专栏第二章,从本章开始正式进入SpringBoot的WEB阶段开发,本章先带你认识yaml配置文件和资源的路径配置原理,以方便在后面的文章中打下基础
804 4