Spring AI 是一個用于 AI 工程的應用框架
Spring AI 是一個用于 AI 工程的應用框架。其目標是將可移植性和模塊化設計等 Spring 生態系統設計原則應用于 AI 領域,并推廣使用 POJO 作為應用程序的構建塊到 AI 領域。
Spring AI 的核心是解決 AI 集成的基本挑戰:將企業數據和 API 與 AI 模型連接起來。
特征
支持所有主要的 AI 模型提供商,例如 Anthropic、OpenAI、Microsoft、Amazon、Google 和 Ollama。支持的模型類型包括
基于Spring AI與Cassandra整合
以下是基于Spring AI與Cassandra整合的實用示例,涵蓋從基礎操作到高級應用場景,代碼均以Spring Boot為框架。
基礎CRUD操作
1. 實體類定義
@Table
public class Product {@PrimaryKeyprivate UUID id;private String name;private double price;// Lombok注解省略
}
2. 插入數據
@Repository
public interface ProductRepository extends CassandraRepository<Product, UUID> {@InsertProduct save(Product product);
}
3. 批量插入
List<Product> products = Arrays.asList(new Product(...));
productRepository.saveAll(products);
4. 按ID查詢
Optional<Product> product = productRepository.findById(uuid);
5. 更新數據
product.setPrice(29.99);
productRepository.save(product);
查詢與條件操作
6. 自定義查詢方法
@Query("SELECT * FROM products WHERE price > ?0 ALLOW FILTERING")
List<Product> findByPriceGreaterThan(double price);
7. 分頁查詢
Page<Product> page = productRepository.findAll(PageRequest.of(0, 10));
8. 排序查詢
Sort sort = Sort.by(Sort.Direction.DESC, "price");
List<Product> products = productRepository.findAll(sort);
9. IN條件查詢
@Query("SELECT * FROM products WHERE id IN ?0")
List<Product> findByIds(List<UUID> ids);
10. 使用CassandraTemplate
cassandraTemplate.select("SELECT * FROM products", Product.class);
高級數據建模
11. 使用UDT(用戶定義類型)
@UserDefinedType("address")
public class Address {private String city;private String street;
}
12. 集合類型字段
@Table
public class User {private Set<String> tags;private Map<String, String> attributes;
}
13. 時間序列數據建模
@PrimaryKeyClass
public class SensorReadingKey {@PrimaryKeyColumn(type = PrimaryKeyType.PARTITIONED)private String sensorId;@PrimaryKeyColumn(type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING)private Instant timestamp;
}
AI集成示例
14. 存儲AI模型輸出
@Table
public class ModelPrediction {@PrimaryKeyprivate UUID id;private String modelName;private Map<String, Double> probabilities;
}
15. 特征向量存儲
@Table
public class FeatureVector {@PrimaryKeyprivate String entityId;private List<Float> vector; // 用于相似性搜索
}
16. 推薦結果緩存
@Table
public class UserRecommendation {@PrimaryKeyprivate String userId;private List<String> recommendedItems;
}
性能優化
17. 批量異步寫入
ListenableFuture<Void> future = cassandraTemplate.insertAsynchron(entities);
18. 輕量級事務
@Insert(ifNotExists = true)
boolean insertIfNotExists(Product product);
19. 物化視圖查詢
@Table
@MaterializedView("products_by_price")
public class ProductByPrice {@PrimaryKeyprivate double price;private UUID productId;
}
錯誤處理與監控
20. 重試策略配置
@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 100))
public void saveWithRetry(Product product) {productRepository.save(product);
}
21. 指標監控
@Timed("cassandra.query.time")
public List<Product> findAllProducts() {return productRepository.findAll();
}
分布式場景
22. 多數據中心配置
spring:data:cassandra:keyspace-name: my_keyspacelocal-datacenter: DC1contact-points: host1,host2
23. 跨分區查詢
@Query("SELECT * FROM products WHERE token(id) > token(?0) LIMIT 100")
List<Product> findAfterToken(UUID lastId);
測試與調試
24. 單元測試配置
@TestConfiguration
@EmbeddedCassandra
static class TestConfig {@BeanCassandraTemplate testTemplate() {return new CassandraTemplate(session);}
}
25. 查詢日志打印
logging:level:org.springframework.data.cassandra.core.CassandraTemplate: DEBUG
以上示例覆蓋了Spring Data Cassandra的核心功能,結合AI場景的特性存儲需求,可根據實際業務擴展修改。注意生產環境中需優化分區鍵設計、添加適當的索引策略。
基于Spring和Azure Vector Search的實例
以下是一些基于Spring和Azure Vector Search的實例示例,涵蓋不同場景和使用方法:
基礎配置與初始化
在application.properties
或application.yml
中配置Azure Vector Search的連接信息:
azure.search.endpoint=https://{your-service-name}.search.windows.net
azure.search.api-key={your-api-key}
azure.search.index-name={your-index-name}
在Spring Boot中注入SearchClient
:
@Bean
public SearchClient searchClient(@Value("${azure.search.endpoint}") String endpoint,@Value("${azure.search.api-key}") String apiKey,@Value("${azure.search.index-name}") String indexName) {return new SearchClientBuilder().endpoint(endpoint).credential(new AzureKeyCredential(apiKey)).indexName(indexName).buildClient();
}
向量搜索基礎示例
使用預生成的向量進行相似性搜索:
public List<SearchResult> searchByVector(float[] vector, int k) {SearchOptions options = new SearchOptions().setVector(new SearchQueryVector().setValue(vector).setKNearestNeighborsCount(k));return searchClient.search(null, options, Context.NONE).stream().collect(Collectors.toList());
}
文本嵌入與搜索
結合Azure OpenAI生成文本嵌入后搜索:
public List<SearchResult> searchByText(String query, int k) {float[] embedding = openAIClient.generateEmbedding(query); // 假設已配置OpenAI客戶端return searchByVector(embedding, k);
}
混合搜索(向量+關鍵詞)
同時使用向量和關鍵詞進行搜索:
public List<SearchResult> hybridSearch(String query, float[] vector, int k) {SearchOptions options = new SearchOptions().setVector(new SearchQueryVector().setValue(vector).setKNearestNeighborsCount(k)).setSearchText(query);return searchClient.search(null, options, Context.NONE).stream().collect(