Spring Boot整合LangChain4j对接通义千问实战,深入理解 Python `ssl` 库:安全通信的基石。

张开发
2026/4/7 4:44:38 15 分钟阅读

分享文章

Spring Boot整合LangChain4j对接通义千问实战,深入理解 Python `ssl` 库:安全通信的基石。
LangChain4j 整合 Spring Boot 实战接入通义千问与 MySQL 会话存储环境准备与依赖配置确保开发环境已安装 JDK 17、Maven 3.6 和 MySQL 5.7。在 Spring Boot 项目的pom.xml中添加核心依赖dependency groupIddev.langchain4j/groupId artifactIdlangchain4j/artifactId version0.24.0/version /dependency dependency groupIddev.langchain4j/groupId artifactIdlangchain4j-qianfan/artifactId version0.24.0/version /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-jpa/artifactId /dependency通义千问 API 配置在application.yml中配置通义千问的访问密钥和端点qianfan: api-key: YOUR_API_KEY secret-key: YOUR_SECRET_KEY endpoint: https://api.qianfan.com/v1/chat/completions创建配置类封装 API 参数Configuration public class QianfanConfig { Value(${qianfan.api-key}) private String apiKey; Value(${qianfan.secret-key}) private String secretKey; Bean public QianfanChatModel chatModel() { return QianfanChatModel.builder() .apiKey(apiKey) .secretKey(secretKey) .build(); } }实现会话存储模型设计 MySQL 实体类存储对话历史Entity Table(name chat_sessions) public class ChatSession { Id private String sessionId; Lob Column(length 65535) private String conversationHistory; private LocalDateTime lastUpdated; }创建 JPA 仓库接口public interface ChatSessionRepository extends JpaRepositoryChatSession, String { }实现会话记忆存储自定义ChatMemoryStore实现与数据库交互Component public class JpaChatMemoryStore implements ChatMemoryStore { private final ChatSessionRepository repository; public void update(String memoryId, ChatMemory memory) { ChatSession session new ChatSession(); session.setSessionId(memoryId); session.setConversationHistory(serialize(memory.messages())); repository.save(session); } private String serialize(ListChatMessage messages) { return new Gson().toJson(messages); } }构建服务层创建对话服务整合组件Service public class ChatService { private final QianfanChatModel chatModel; private final ChatMemoryStore memoryStore; public String chat(String sessionId, String userInput) { ChatMemory memory MemoryChatMemory.builder() .id(sessionId) .chatMemoryStore(memoryStore) .build(); Assistant assistant AiServices.builder(Assistant.class) .chatLanguageModel(chatModel) .chatMemory(memory) .build(); return assistant.chat(userInput); } }控制器层实现创建 REST API 端点RestController RequestMapping(/api/chat) public class ChatController { private final ChatService chatService; PostMapping(/{sessionId}) public ResponseEntityString handleChat( PathVariable String sessionId, RequestBody String message) { String response chatService.chat(sessionId, message); return ResponseEntity.ok(response); } }会话管理增强添加自动清理过期会话的定时任务Scheduled(fixedRate 3600000) // 每小时执行 Transactional public void cleanupExpiredSessions() { LocalDateTime threshold LocalDateTime.now().minusDays(7); repository.deleteByLastUpdatedBefore(threshold); }性能优化建议对于高频访问场景建议添加 Redis 缓存层Cacheable(value chatSessions, key #sessionId) public ChatMemory loadMemory(String sessionId) { // 数据库查询逻辑 }配置缓存过期策略spring: cache: redis: time-to-live: 1800000 # 30分钟异常处理机制全局异常处理器增强健壮性ControllerAdvice public class ChatExceptionHandler { ExceptionHandler(QianfanException.class) public ResponseEntityErrorResponse handleApiError(QianfanException ex) { return ResponseEntity.status(502).body(new ErrorResponse(ex.getMessage())); } }测试验证方案集成测试示例SpringBootTest class ChatServiceTest { Autowired private ChatService service; Test void shouldMaintainConversationFlow() { String sessionId test-session; String response1 service.chat(sessionId, 你好); String response2 service.chat(sessionId, 刚才我说了什么); assertThat(response2).contains(你好); } }https://github.com/cbar1239/nro_fwvi/blob/main/README.mdhttps://raw.githubusercontent.com/cbar1239/nro_fwvi/main/README.mdhttps://github.com/pjongfreemen/c6v_xxtkhttps://github.com/pjongfreemen/c6v_xxtk/blob/main/README.mdhttps://raw.githubusercontent.com/pjongfreemen/c6v_xxtk/main/README.md

更多文章