Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,14 @@ public void init() {

try {
// 执行 Lua 脚本获取 workerId 和 datacenterId
List<Long> result = stringRedisTemplate.execute(script, Collections.emptyList());
List<String> strResult = stringRedisTemplate.execute(script, Collections.emptyList());

if (CollUtil.isEmpty(result) || result.size() != 2) {
if (CollUtil.isEmpty(strResult) || strResult.size() != 2) {
throw new RuntimeException("从Redis获取WorkerId和DataCenterId失败");
}

Long workerId = result.get(0);
Long datacenterId = result.get(1);
Long workerId = Long.parseLong(strResult.get(0));
Long datacenterId = Long.parseLong(strResult.get(1));

// 注册到 Hutool 的 IdUtil
Snowflake snowflake = new Snowflake(workerId, datacenterId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ local datacenterId = redis.call('GET', datacenter_key)
if not datacenterId then
datacenterId = math.floor(math.random() * 32) -- 随机选择 0-31
redis.call('SET', datacenter_key, datacenterId)
else
datacenterId = tonumber(datacenterId)
end

return {workerId, datacenterId}
18 changes: 18 additions & 0 deletions chat-agent-infra/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,30 @@
<artifactId>okhttp</artifactId>
</dependency>

<!-- PgVector -->
<dependency>
<groupId>com.pgvector</groupId>
<artifactId>pgvector</artifactId>
</dependency>

<!-- HikariCP (pgvector uses it via JdbcTemplate) -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>

<!-- Milvus -->
<dependency>
<groupId>io.milvus</groupId>
<artifactId>milvus-sdk-java</artifactId>
</dependency>

<!-- PostgreSQL JDBC -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>

<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

Expand All @@ -28,9 +29,12 @@
* <p>
* 通过 Spring 容器统一创建并管理 {@link MilvusClientV2} 实例,用于向量数据的增删改查、索引管理等操作
* 支持通过配置文件设置连接地址与可选的访问令牌
* <p>
* 默认禁用,如需启用请设置 {@code agent.milvus.enabled=true}
*/
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "agent", name = "milvus.enabled", havingValue = "true", matchIfMissing = false)
public class MilvusConfig {

private final MilvusProperties milvusProperties;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,20 @@
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.util.ArrayList;
import java.util.List;

/**
* Milvus 向量数据库配置属性
* <p>
* 默认禁用,如需启用请设置 {@code agent.milvus.enabled=true}
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "milvus")
@ConditionalOnProperty(prefix = "agent", name = "milvus.enabled", havingValue = "true", matchIfMissing = false)
public class MilvusProperties {

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import io.milvus.v2.service.collection.response.ListCollectionsResp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
Expand All @@ -37,10 +38,13 @@
* Milvus 向量空间管理实现
* <p>
* 实现 {@link VectorStoreAdmin} 接口,负责 Collection 的 DDL 操作
* <p>
* 默认禁用,如需启用请设置 {@code agent.milvus.enabled=true}
*/
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "agent", name = "milvus.enabled", havingValue = "true", matchIfMissing = false)
public class MilvusVectorStoreAdmin implements VectorStoreAdmin {

private final MilvusClientV2 milvusClient;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import io.milvus.v2.service.vector.response.SearchResp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
Expand All @@ -45,10 +46,13 @@
* Milvus 向量存储服务实现
* <p>
* 实现 {@link VectorStoreService} 接口,封装 Milvus SDK v2 的增删改查操作
* <p>
* 默认禁用,如需启用请设置 {@code agent.milvus.enabled=true}
*/
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "agent", name = "milvus.enabled", havingValue = "true", matchIfMissing = false)
public class MilvusVectorStoreService implements VectorStoreService {

private final MilvusClientV2 milvusClient;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.sai.chat.agent.infra.vector;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
* PgVector 向量数据库客户端配置
* <p>
* 通过 Spring 容器统一创建并管理 {@link DataSource} 实例,用于向量数据的增删改查、索引管理等操作。
* 支持通过配置文件设置连接地址与访问凭证。
* <p>
* 初始化时自动:
* - 启用 pgvector 扩展
* - 创建默认向量存储表(如不存在)
*/
@Slf4j
@Configuration
@RequiredArgsConstructor
public class PgVectorConfig {

private final PgVectorProperties pgVectorProperties;

@Bean
public DataSource pgVectorDataSource() {
PgVectorProperties.TableConfig tableConfig = pgVectorProperties.getTable();
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(pgVectorProperties.getJdbcUrl());
hikariConfig.setUsername(pgVectorProperties.getUsername());
hikariConfig.setPassword(pgVectorProperties.getPassword());
hikariConfig.setPoolName("PgVectorHikariPool");
hikariConfig.setMaximumPoolSize(10);
hikariConfig.setMinimumIdle(2);
hikariConfig.setConnectionTimeout(5000);
hikariConfig.setIdleTimeout(600000);
hikariConfig.setMaxLifetime(1800000);
hikariConfig.setConnectionTestQuery("SELECT 1");
log.info("PgVector 数据源配置完成, jdbcUrl={}", pgVectorProperties.getJdbcUrl());
return new HikariDataSource(hikariConfig);
}

@Bean
public JdbcTemplate pgVectorJdbcTemplate(DataSource pgVectorDataSource) {
return new JdbcTemplate(pgVectorDataSource);
}

@Bean
public PgVectorInitializer pgVectorInitializer(DataSource pgVectorDataSource,
PgVectorProperties pgVectorProperties) {
return new PgVectorInitializer(pgVectorDataSource, pgVectorProperties);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.sai.chat.agent.infra.vector;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
* PgVector 初始化器
* <p>
* 在 Spring 容器初始化时执行以下一次性操作:
* 1. 启用 pgvector 扩展(CREATE EXTENSION IF NOT EXISTS vector)
* 2. 创建默认向量存储表(如不存在)
*/
@Slf4j
@RequiredArgsConstructor
public class PgVectorInitializer {

private final DataSource dataSource;
private final PgVectorProperties pgVectorProperties;

@PostConstruct
public void init() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
PgVectorProperties.TableConfig tableConfig = pgVectorProperties.getTable();
String tableName = tableConfig.getDefaultName();

enableExtension(jdbcTemplate);
createTableIfAbsent(jdbcTemplate, tableName, tableConfig.getDimension());
log.info("PgVector 初始化完成, table={}, dimension={}", tableName, tableConfig.getDimension());
}

private void enableExtension(JdbcTemplate jdbcTemplate) {
try {
jdbcTemplate.execute("CREATE EXTENSION IF NOT EXISTS vector");
log.debug("pgvector 扩展启用成功");
} catch (Exception e) {
log.warn("pgvector 扩展启用失败,请确认 PostgreSQL 已安装 pgvector 插件: {}", e.getMessage());
}
}

private void createTableIfAbsent(JdbcTemplate jdbcTemplate, String tableName, int dimension) {
if (tableExists(jdbcTemplate, tableName)) {
log.debug("表已存在,跳过创建: {}", tableName);
return;
}

String sql = """
CREATE TABLE IF NOT EXISTS %s (
id BIGSERIAL PRIMARY KEY,
doc_id VARCHAR(64) NOT NULL,
content TEXT,
embedding VECTOR(%d),
metadata JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""".formatted(tableName, dimension);

jdbcTemplate.execute(sql);
log.info("PgVector 表创建成功, table={}, dimension={}", tableName, dimension);

String indexType = pgVectorProperties.getTable().getIndexType();
createIndexIfAbsent(jdbcTemplate, tableName, dimension, indexType);
}

private void createIndexIfAbsent(JdbcTemplate jdbcTemplate, String tableName,
int dimension, String indexType) {
String indexName = tableName + "_embedding_idx";
if (indexExists(jdbcTemplate, indexName)) {
log.debug("索引已存在,跳过创建: {}", indexName);
return;
}

String metricType = pgVectorProperties.getTable().getMetricType();
String vectorField = "embedding";

String indexSql = switch (indexType.toLowerCase()) {
case "ivfflat" -> String.format(
"CREATE INDEX IF NOT EXISTS %s ON %s USING ivfflat (%s %s) WITH (lists = 100)",
indexName, tableName, vectorField, metricType);
case "hnsw" -> {
int m = pgVectorProperties.getTable().getM();
int efConstruction = pgVectorProperties.getTable().getEfConstruction();
yield String.format(
"CREATE INDEX IF NOT EXISTS %s ON %s USING hnsw (%s %s) WITH (m = %d, ef_construction = %d)",
indexName, tableName, vectorField, metricType, m, efConstruction);
}
default -> {
log.debug("索引类型为 none,跳过索引创建");
yield null;
}
};

if (indexSql != null) {
jdbcTemplate.execute(indexSql);
log.info("PgVector 索引创建成功, index={}, type={}", indexName, indexType);
}
}

private boolean tableExists(JdbcTemplate jdbcTemplate, String tableName) {
try (Connection conn = dataSource.getConnection()) {
DatabaseMetaData metaData = conn.getMetaData();
String schema = conn.getSchema();
try (ResultSet rs = metaData.getTables(null, schema, tableName, new String[]{"TABLE"})) {
return rs.next();
}
} catch (SQLException e) {
log.warn("检查表是否存在时出错: {}", e.getMessage());
return false;
}
}

private boolean indexExists(JdbcTemplate jdbcTemplate, String indexName) {
try (Connection conn = dataSource.getConnection()) {
DatabaseMetaData metaData = conn.getMetaData();
String schema = conn.getSchema();
try (ResultSet rs = metaData.getIndexInfo(null, schema, null, true, false)) {
while (rs.next()) {
if (indexName.equals(rs.getString("INDEX_NAME"))) {
return true;
}
}
}
} catch (SQLException e) {
log.warn("检查索引是否存在时出错: {}", e.getMessage());
}
return false;
}
}
Loading
Loading