SpringAI实战:5分钟搞定智能天气查询+用户注册的AI客服系统(Spring Boot 3.5.0版)
最近在帮几个初创团队做技术选型,发现他们普遍面临一个困境:既想快速上线一个具备AI能力的客服系统来提升用户体验,又担心成本失控和技术复杂度。传统的方案要么依赖昂贵的云服务API,要么需要投入大量时间搭建复杂的微服务架构。直到我深入研究了SpringAI,尤其是它的@Tool注解和本地模型集成能力,才发现原来用Spring Boot 3.5.0版本,真的能在5分钟内搭建出一个可用的智能客服原型。
这个方案的核心思路是最小可行产品——我们不追求大而全的功能,而是聚焦于两个最高频的业务场景:天气查询和用户注册。通过Ollama本地模型替代付费API,结合阿里云DashScope的密钥安全配置技巧,你不仅能快速看到效果,还能确保系统的可扩展性和安全性。下面我就把自己踩过坑之后的完整实现路径分享给你。
1. 环境准备与项目初始化
1.1 技术栈选型与依赖配置
我选择Spring Boot 3.5.0作为基础框架,主要是看中了它对Java 17的完整支持以及更好的性能表现。SpringAI 1.0.0版本虽然相对较新,但已经足够稳定,特别是它的@Tool注解机制,让工具调用变得异常简单。
先来看看pom.xml的关键依赖配置:
<properties>
<java.version>17</java.version>
<spring-ai.version>1.0.0</spring-ai.version>
<spring-boot.version>3.5.0</spring-boot.version>
</properties>
<dependencies>
<!-- SpringAI核心依赖 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
<!-- 阿里云DashScope模型(备用方案) -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
<version>1.0.0.1</version>
</dependency>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 数据持久化(简化版用H2,生产用MySQL) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 配置处理器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
这里有个细节需要注意:SpringAI的依赖管理在1.0.0版本后变得更加规范,我们不需要再手动指定版本号,Spring Boot的BOM会自动管理。但阿里云的DashScope starter目前还需要显式指定版本。
1.2 Ollama本地模型部署
Ollama是我测试过的本地模型部署工具中最简单的一个。它支持Docker一键部署,而且模型库相当丰富。下面是我常用的启动脚本:
# 拉取Ollama镜像
docker pull ollama/ollama:latest
# 运行容器(注意挂载目录持久化模型)
docker run -d \
--name ollama \
-v ~/.ollama:/root/.ollama \
-p 11434:11434 \
--restart unless-stopped \
ollama/ollama:latest
# 进入容器安装模型(这里选择轻量级的llama3:8b)
docker exec -it ollama ollama pull llama3:8b
提示:如果你在开发环境遇到网络问题,可以考虑使用国内镜像源。在容器内执行
export OLLAMA_HOST=0.0.0.0并重启服务。
模型下载完成后,可以通过简单的curl命令测试:
curl http://localhost:11434/api/generate -d '{
"model": "llama3:8b",
"prompt": "Hello, how are you?",
"stream": false
}'
如果看到返回的JSON响应,说明模型部署成功。我比较过几个模型,llama3:8b在响应速度和准确性上平衡得最好,特别适合客服场景。
1.3 基础配置文件
application.yml的配置需要特别注意安全性和灵活性:
spring:
application:
name: ai-customer-service
# 数据库配置(开发环境用H2,生产环境注释掉切换MySQL)
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password:
# H2控制台(仅开发环境开启)
h2:
console:
enabled: true
path: /h2-console
# AI模型配置 - 优先级:本地Ollama > 阿里云DashScope
ai:
# 主模型配置
ollama:
base-url: http://localhost:11434
chat:
options:
model: llama3:8b
temperature: 0.7 # 控制创造性,客服场景建议0.3-0.7
top-p: 0.9
max-tokens: 500
# 备用模型配置(当Ollama不可用时自动切换)
dashscope:
api-key: ${DASHSCOPE_API_KEY:} # 从环境变量读取
chat:
options:
model: qwen-max
temperature: 0.3
# 自定义业务配置
customer-service:
weather:
cache-ttl: 300 # 天气数据缓存5分钟
api-key: ${WEATHER_API_KEY:}
security:
rate-limit:
enabled: true
requests-per-minute: 60 # 每分钟最多60次请求
这里我采用了环境变量注入的方式管理敏感信息,这是生产环境的最佳实践。你可以在启动时通过-D参数或.env文件设置这些变量。
2. SpringAI核心概念与@Tool注解实战
2.1 ChatClient的配置与定制
SpringAI的ChatClient是整个系统的核心,它封装了与AI模型的交互逻辑。我的配置方式与官方文档略有不同,更注重实用性和可维护性:
@Configuration
@EnableConfigurationProperties(AiModelProperties.class)
public class AiConfig {
@Bean
public ChatClient chatClient(
OllamaChatModel ollamaModel,
@Autowired(required = false) DashScopeChatModel dashscopeModel,
ChatMemory chatMemory,
List<Object> toolBeans) {
// 构建ChatClient,优先使用Ollama,失败时降级到DashScope
ChatClient.Builder builder = ChatClient.builder(ollamaModel)
.defaultSystem("""
你是XX公司的智能客服助手,请以专业、友好的态度与用户交流。
你可以帮助用户:
1. 查询全国主要城市的实时天气信息
2. 注册新的用户账号
3. 解答产品相关问题
4. 提供技术支持
注意事项:
- 如果用户的问题超出你的能力范围,请如实告知
- 涉及用户隐私信息时,必须明确告知使用目的
- 保持回答简洁明了,避免冗长
""")
.defaultAdvisors(
PromptChatMemoryAdvisor.builder(chatMemory).build(),
new RateLimitAdvisor() // 自定义的限流顾问
);
// 动态注册所有标记了@Tool注解的Bean
if (!CollectionUtils.isEmpty(toolBeans)) {
builder.defaultTools(toolBeans.toArray());
}
// 设置备用模型
if (dashscopeModel != null) {
builder.fallbackModel(dashscopeModel);
}
return builder.build();
}
@Bean
public ChatMemory chatMemory() {
// 使用消息窗口记忆,保留最近20轮对话
return MessageWindowChatMemory.builder()
.maxMessages(20)
.capacity(1000) // 字符数限制
.build();
}
}
这里我引入了几个关键改进:
- 模型降级机制:当本地Ollama服务不可用时,自动切换到阿里云DashScope
- 自定义Advisor:添加了限流、日志记录等横切关注点
- 动态工具注册:通过扫描所有
@Tool注解的Bean,避免硬编码
2.2 @Tool注解的深度应用
@Tool注解是SpringAI最强大的特性之一,它允许你将任意Java方法暴露给AI模型调用。但很多开发者只用了基础功能,下面是我的进阶用法:
@Service
@Slf4j
public class CustomerServiceTool {
private final WeatherService weatherService;
private final UserService userService;
private final RateLimiter rateLimiter;
public CustomerServiceTool(WeatherService weatherService,
UserService userService) {
this.weatherService = weatherService;
this.userService = userService;
this.rateLimiter = RateLimiter.create(10.0); // 每秒10个请求
}
@Tool(
name = "query_weather",
description = "查询指定城市的实时天气信息,包括温度、湿度、天气状况等",
inputSchema = @Schema(
description = "城市天气查询参数",
requiredProperties = {"city"},
properties = {
@Property(name = "city", description = "城市名称,如'北京'、'上海'"),
@Property(name = "include_forecast", description = "是否包含天气预报", type = "boolean")
}
)
)
public WeatherResponse getWeather(
@ToolParam(description = "城市名称,支持中文和拼音") String city,
@ToolParam(description = "是否包含未来3天预报", required = false)
@DefaultValue("false") Boolean includeForecast) {
// 限流检查
if (!rateLimiter.tryAcquire()) {
throw new RateLimitExceededException("天气查询频率过高,请稍后再试");
}
log.info("AI工具调用:查询{}的天气,包含预报:{}", city, includeForecast);
WeatherInfo current = weatherService.getCurrentWeather(city);
WeatherResponse response = WeatherResponse.builder()
.city(city)
.current(current)
.timestamp(LocalDateTime.now())
.build();
if (Boolean.TRUE.equals(includeForecast)) {
List<WeatherInfo> forecast = weatherService.getForecast(city, 3);
response.setForecast(forecast);
}
return response;
}
@Tool(
name = "register_user",
description = "注册新用户账号,需要用户名和密码",
inputSchema = @Schema(
description = "用户注册信息",
requiredProperties = {"username", "password"},
properties = {
@Property(name = "username", description = "用户名,4-20位字母数字组合"),
@Property(name = "password", description = "密码,至少8位,包含字母和数字"),
@Property(name = "email", description = "邮箱地址(可选)", type = "string")
}
)
)
public RegistrationResult registerUser(
@ToolParam(description = "用户名,唯一标识") String username,
@ToolParam(description = "登录密码") String password,
@ToolParam(description = "电子邮箱", required = false) String email) {
// 密码强度验证
if (!isPasswordValid(password)) {
throw new IllegalArgumentException("密码必须包含字母和数字,且长度至少8位");
}
User user = User.builder()
.username(username)
.password(passwordEncoder.encode(password))
.email(email)
.status(UserStatus.ACTIVE)
.createdAt(LocalDateTime.now())
.build();
User savedUser = userService.createUser(user);
return RegistrationResult.builder()
.success(true)
.userId(savedUser.getId())
.message("用户注册成功")
.suggestions(List.of(
"建议立即验证邮箱",
"完善个人信息可获得更好体验"
))
.build();
}
private boolean isPasswordValid(String password) {
if (password == null || password.length() < 8) {
return false;
}
return password.matches("^(?=.*[A-Za-z])(?=.*\\d).+$");
}
}
我在这里做了几个重要优化:
- 详细的Schema定义:通过
@Schema和@Property注解提供丰富的元数据,帮助AI模型更好地理解工具用途 - 输入验证:在工具方法内部进行业务逻辑验证,而不是依赖AI模型
- 结构化响应:返回丰富的对象,包含成功状态、用户ID、提示信息等
- 限流保护:防止工具被恶意频繁调用
2.3 工具调用的错误处理与降级
在实际运行中,工具调用可能会失败。我设计了一套完整的错误处理机制:
@ControllerAdvice
@Slf4j
public class ToolExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ToolErrorResponse> handleToolException(Exception ex) {
log.error("工具调用异常", ex);
ToolErrorResponse error;
if (ex instanceof RateLimitExceededException) {
error = ToolErrorResponse.rateLimit(ex.getMessage());
} else if (ex instanceof IllegalArgumentException) {
error = ToolErrorResponse.badRequest(ex.getMessage());
} else if (ex instanceof ServiceUnavailableException) {
error = ToolErrorResponse.serviceUnavailable("服务暂时不可用,请稍后重试");
} else {
error = ToolErrorResponse.internalError("系统内部错误");
}
// 记录到监控系统
Metrics.counter("tool_errors_total",
"tool", getToolNameFromStackTrace(ex))
.increment();
return ResponseEntity
.status(error.getStatusCode())
.body(error);
}
@ExceptionHandler(ToolExecutionException.class)
public String handleAiToolException(ToolExecutionException ex) {
// 返回AI可理解的错误描述
return String.format("""
抱歉,执行操作时遇到问题:
错误类型:%s
建议操作:%s
如需人工帮助,请回复"转人工"
""",
ex.getErrorType(),
ex.getSuggestion());
}
private String getToolNameFromStackTrace(Exception ex) {
// 从堆栈跟踪中提取工具名称
return Arrays.stream(ex.getStackTrace())
.filter(frame -> frame.getClassName().contains("Tool"))
.findFirst()
.map(StackTraceElement::getMethodName)
.orElse("unknown");
}
}
这套错误处理机制有几个亮点:
- 分层处理:根据异常类型返回不同的HTTP状态码
- AI友好:
ToolExecutionException返回AI能直接使用的错误描述 - 监控集成:自动记录错误指标,便于后续分析
- 用户体验:提供明确的错误信息和操作建议
3. 天气查询服务的实现细节
3.1 天气数据模型设计
天气服务看似简单,但要做好需要考虑很多细节。我的设计思路是:缓存 + 降级 + 多数据源。
首先定义数据模型:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WeatherInfo {
private String city;
private String cityCode;
// 基础信息
private Double temperature; // 温度(摄氏度)
private Double feelsLike; // 体感温度
private Integer humidity; // 湿度百分比
private String description; // 天气描述
private String icon; // 天气图标代码
// 风信息
private Double windSpeed; // 风速(米/秒)
private String windDirection; // 风向
private Integer windDegree; // 风向角度
// 大气信息
private Double pressure; // 气压(hPa)
private Integer visibility; // 能见度(米)
private Double precipitation; // 降水量(mm)
// 时间信息
private LocalDateTime observationTime;
private LocalDateTime sunrise;
private LocalDateTime sunset;
// 空气质量(可选)
private AirQuality airQuality;
// 扩展信息
private Map<String, Object> additionalInfo;
@Data
@Builder
public static class AirQuality {
private Integer aqi; // 空气质量指数
private String level; // 等级
private String primaryPollutant; // 主要污染物
private Map<String, Double> pollutants; // 各污染物浓度
}
}
这个模型设计考虑了扩展性,additionalInfo字段可以存储任何第三方API返回的额外数据。
3.2 多数据源天气服务实现
我实现了支持多个天气数据源的服务,并提供了自动降级机制:
@Service
@Slf4j
public class WeatherServiceImpl implements WeatherService {
private final List<WeatherDataSource> dataSources;
private final Cache<String, WeatherInfo> weatherCache;
private final RetryTemplate retryTemplate;
public WeatherServiceImpl(
@Qualifier("openWeatherSource") WeatherDataSource primarySource,
@Qualifier("heWeatherSource") WeatherDataSource fallbackSource,
CacheManager cacheManager) {
this.dataSources = List.of(primarySource, fallbackSource);
this.weatherCache = cacheManager.getCache("weather");
this.retryTemplate = RetryTemplate.builder()
.maxAttempts(3)
.fixedBackoff(1000)
.retryOn(ServiceUnavailableException.class)
.build();
}
@Override
@Cacheable(value = "weather", key = "#city", unless = "#result == null")
public WeatherInfo getCurrentWeather(String city) {
log.debug("查询天气:{}", city);
// 1. 检查缓存
WeatherInfo cached = weatherCache.get(city, WeatherInfo.class);
if (cached != null && !isCacheExpired(cached)) {
log.debug("从缓存返回天气数据:{}", city);
return cached;
}
// 2. 重试机制获取最新数据
return retryTemplate.execute(context -> {
int attempt = context.getRetryCount() + 1;
WeatherDataSource source = dataSources.get(
Math.min(attempt - 1, dataSources.size() - 1)
);
log.info("第{}次尝试,使用数据源:{}", attempt, source.getClass().getSimpleName());
try {
WeatherInfo weather = source.fetchCurrentWeather(city);
// 数据验证
validateWeatherData(weather);
// 更新缓存
weatherCache.put(city, weather);
// 记录指标
Metrics.counter("weather_queries_total",
"source", source.getClass().getSimpleName(),
"city", city)
.increment();
return weather;
} catch (Exception e) {
log.warn("数据源{}查询失败:{}", source.getClass().getSimpleName(), e.getMessage());
if (attempt >= dataSources.size()) {
throw new ServiceUnavailableException("所有天气数据源均不可用");
}
throw e;
}
});
}
@Override
public List<WeatherInfo> getForecast(String city, int days) {
if (days < 1 || days > 7) {
throw new IllegalArgumentException("预报天数必须在1-7之间");
}
String cacheKey = String.format("%s_forecast_%d", city, days);
return retryTemplate.execute(context -> {
// 实现逻辑类似getCurrentWeather,支持分页获取预报
// ...
});
}
private boolean isCacheExpired(WeatherInfo weather) {
if (weather == null || weather.getObservationTime() == null) {
return true;
}
Duration duration = Duration.between(
weather.getObservationTime(),
LocalDateTime.now()
);
return duration.toMinutes() > 10; // 10分钟过期
}
private void validateWeatherData(WeatherInfo weather) {
if (weather == null) {
throw new IllegalStateException("天气数据为空");
}
if (weather.getTemperature() < -50 || weather.getTemperature() > 60) {
throw new IllegalStateException("温度数据异常:" + weather.getTemperature());
}
if (weather.getHumidity() < 0 || weather.getHumidity() > 100) {
throw new IllegalStateException("湿度数据异常:" + weather.getHumidity());
}
}
}
这个实现有几个关键技术点:
- 多数据源降级:主数据源失败时自动切换到备用源
- 智能缓存:基于数据新鲜度的缓存策略
- 重试机制:使用Spring Retry实现自动重试
- 数据验证:确保返回数据的合理性
- 监控指标:记录查询统计信息
3.3 天气数据源接口实现
以OpenWeatherMap为例的数据源实现:
@Component("openWeatherSource")
@Slf4j
public class OpenWeatherDataSource implements WeatherDataSource {
private final RestTemplate restTemplate;
private final String apiKey;
private final String baseUrl;
public OpenWeatherDataSource(
@Value("${customer-service.weather.api-key}") String apiKey,
@Value("${customer-service.weather.openweather.url:https://api.openweathermap.org}")
String baseUrl) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.restTemplate = new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(5))
.setReadTimeout(Duration.ofSeconds(10))
.additionalInterceptors(new LoggingInterceptor())
.build();
}
@Override
public WeatherInfo fetchCurrentWeather(String city) {
try {
String url = String.format(
"%s/data/2.5/weather?q=%s&appid=%s&units=metric&lang=zh_cn",
baseUrl, URLEncoder.encode(city, StandardCharsets.UTF_8), apiKey
);
ResponseEntity<OpenWeatherResponse> response = restTemplate.exchange(
url, HttpMethod.GET, null, OpenWeatherResponse.class);
if (!response.getStatusCode().is2xxSuccessful() || response.getBody() == null) {
throw new ServiceUnavailableException("天气API响应异常");
}
return convertToWeatherInfo(response.getBody());
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new CityNotFoundException("城市不存在: " + city);
}
throw new ServiceUnavailableException("天气服务暂时不可用");
} catch (Exception e) {
log.error("获取天气数据失败", e);
throw new ServiceUnavailableException("天气服务异常");
}
}
private WeatherInfo convertToWeatherInfo(OpenWeatherResponse response) {
return WeatherInfo.builder()
.city(response.getName())
.cityCode(String.valueOf(response.getId()))
.temperature(response.getMain().getTemp())
.feelsLike(response.getMain().getFeelsLike())
.humidity(response.getMain().getHumidity())
.description(response.getWeather().get(0).getDescription())
.icon(response.getWeather().get(0).getIcon())
.windSpeed(response.getWind().getSpeed())
.windDegree(response.getWind().getDeg())
.pressure(response.getMain().getPressure())
.visibility(response.getVisibility())
.observationTime(LocalDateTime.now())
.additionalInfo(Map.of(
"openweather_id", response.getId(),
"coordinates", Map.of(
"lat", response.getCoord().getLat(),
"lon", response.getCoord().getLon()
)
))
.build();
}
// 内部类用于解析OpenWeatherMap响应
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
private static class OpenWeatherResponse {
private Long id;
private String name;
private Coord coord;
private List<Weather> weather;
private Main main;
private Wind wind;
private Integer visibility;
private Long dt;
@Data
public static class Coord {
private Double lon;
private Double lat;
}
@Data
public static class Weather {
private String main;
private String description;
private String icon;
}
@Data
public static class Main {
private Double temp;
private Double feelsLike;
private Integer pressure;
private Integer humidity;
}
@Data
public static class Wind {
private Double speed;
private Integer deg;
}
}
}
这个实现包含了完整的错误处理、数据转换和日志记录。我还添加了一个LoggingInterceptor来记录请求详情,便于调试。
4. 用户注册系统的安全实现
4.1 用户模型与数据层设计
用户系统最核心的是安全性。我采用了分层验证的策略:
@Entity
@Table(name = "users",
indexes = {
@Index(name = "idx_username", columnList = "username", unique = true),
@Index(name = "idx_email", columnList = "email", unique = true),
@Index(name = "idx_status", columnList = "status")
})
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 50)
@Pattern(regexp = "^[a-zA-Z0-9_]{4,20}$",
message = "用户名必须是4-20位字母、数字或下划线")
private String username;
@Column(nullable = false)
@JsonIgnore // 序列化时忽略密码
private String password;
@Column(length = 100)
@Email(message = "邮箱格式不正确")
private String email;
@Column(length = 20)
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
private String phone;
@Enumerated(EnumType.STRING)
@Column(length = 20, nullable = false)
@Builder.Default
private UserStatus status = UserStatus.PENDING; // 默认待激活
@Enumerated(EnumType.STRING)
@Column(length = 20)
private UserRole role;
@Column(name = "failed_attempts")
@Builder.Default
private Integer failedAttempts = 0;
@Column(name = "last_login_at")
private LocalDateTime lastLoginAt;
@Column(name = "locked_until")
private LocalDateTime lockedUntil;
@Column(name = "created_at", nullable = false, updatable = false)
@CreationTimestamp
private LocalDateTime createdAt;
@Column(name = "updated_at")
@UpdateTimestamp
private LocalDateTime updatedAt;
@Version
private Long version; // 乐观锁
public enum UserStatus {
PENDING, // 待激活
ACTIVE, // 活跃
INACTIVE, // 未激活
LOCKED, // 已锁定
DELETED // 已删除
}
public enum UserRole {
USER, // 普通用户
VIP, // VIP用户
ADMIN // 管理员
}
/**
* 检查账户是否被锁定
*/
public boolean isLocked() {
if (lockedUntil == null) {
return false;
}
return LocalDateTime.now().isBefore(lockedUntil);
}
/**
* 增加失败尝试次数
*/
public void incrementFailedAttempts() {
this.failedAttempts++;
// 连续失败5次锁定30分钟
if (this.failedAttempts >= 5) {
this.lockedUntil = LocalDateTime.now().plusMinutes(30);
this.status = UserStatus.LOCKED;
}
}
/**
* 重置失败尝试次数
*/
public void resetFailedAttempts() {
this.failedAttempts = 0;
this.lockedUntil = null;
if (this.status == UserStatus.LOCKED) {
this.status = UserStatus.ACTIVE;
}
}
}
这个用户模型设计考虑了企业级应用的需求:
- 数据完整性:使用JPA注解确保数据库约束
- 安全性:密码字段使用
@JsonIgnore避免泄露 - 业务逻辑:内置账户锁定机制
- 审计跟踪:创建时间、更新时间自动维护
- 并发控制:乐观锁防止并发更新问题
4.2 用户服务的安全实现
用户服务的核心是安全,我实现了多层防护:
@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final RateLimiter registrationLimiter;
private final EventPublisher eventPublisher;
public UserServiceImpl(UserRepository userRepository,
PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
// 注册限流:每分钟最多10次注册
this.registrationLimiter = RateLimiter.create(10.0 / 60.0);
this.eventPublisher = ApplicationEventPublisher::publishEvent;
}
@Override
public User createUser(User user) {
// 1. 限流检查
if (!registrationLimiter.tryAcquire()) {
throw new RateLimitExceededException("注册频率过高,请稍后再试");
}
// 2. 数据验证
validateUser(user);
// 3. 唯一性检查
checkUniqueness(user);
// 4. 密码加密
user.setPassword(passwordEncoder.encode(user.getPassword()));
// 5. 保存用户
User savedUser = userRepository.save(user);
// 6. 发布注册事件
eventPublisher.publishEvent(new UserRegisteredEvent(savedUser));
// 7. 记录审计日志
log.info("用户注册成功:{} (ID: {})", savedUser.getUsername(), savedUser.getId());
return savedUser;
}
@Override
public Optional<User> authenticate(String username, String password) {
return userRepository.findByUsername(username)
.map(user -> {
// 检查账户状态
if (user.getStatus() == UserStatus.LOCKED && user.isLocked()) {
throw new AccountLockedException("账户已被锁定,请30分钟后再试");
}
if (user.getStatus() != UserStatus.ACTIVE) {
throw new AccountInactiveException("账户未激活");
}
// 验证密码
if (passwordEncoder.matches(password, user.getPassword())) {
// 认证成功
user.resetFailedAttempts();
user.setLastLoginAt(LocalDateTime.now());
userRepository.save(user);
log.info("用户登录成功:{}", username);
return user;
} else {
// 认证失败
user.incrementFailedAttempts();
userRepository.save(user);
log.warn("用户登录失败:{},失败次数:{}",
username, user.getFailedAttempts());
throw new AuthenticationFailedException("用户名或密码错误");
}
})
.or(() -> {
// 用户不存在也记录日志(防止用户枚举攻击)
log.warn("尝试登录不存在的用户:{}", username);
throw new AuthenticationFailedException("用户名或密码错误");
});
}
private void validateUser(User user) {
// 使用Hibernate Validator
Set<ConstraintViolation<User>> violations = Validation.buildDefaultValidatorFactory()
.getValidator()
.validate(user);
if (!violations.isEmpty()) {
String message = violations.stream()
.map(v -> v.getPropertyPath() + ": " + v.getMessage())
.collect(Collectors.joining(", "));
throw new ValidationException("用户数据验证失败: " + message);
}
// 自定义业务验证
if (user.getPassword().length() < 8) {
throw new ValidationException("密码长度至少8位");
}
if (!user.getPassword().matches("^(?=.*[A-Za-z])(?=.*\\d).+$")) {
throw new ValidationException("密码必须包含字母和数字");
}
}
private void checkUniqueness(User user) {
// 检查用户名唯一性
if (userRepository.existsByUsername(user.getUsername())) {
throw new DuplicateUserException("用户名已存在");
}
// 检查邮箱唯一性(如果提供了邮箱)
if (user.getEmail() != null &&
userRepository.existsByEmail(user.getEmail())) {
throw new DuplicateUserException("邮箱已被注册");
}
// 检查手机号唯一性(如果提供了手机号)
if (user.getPhone() != null &&
userRepository.existsByPhone(user.getPhone())) {
throw new DuplicateUserException("手机号已被注册");
}
}
@Override
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.findById(id)
.ifPresent(user -> {
// 软删除
user.setStatus(UserStatus.DELETED);
userRepository.save(user);
log.info("用户已删除:{} (ID: {})", user.getUsername(), id);
// 发布删除事件
eventPublisher.publishEvent(new UserDeletedEvent(user));
});
}
@Override
@Cacheable(value = "users", key = "#id", unless = "#result == null")
public Optional<User> getUserById(Long id) {
return userRepository.findById(id)
.filter(user -> user.getStatus() != UserStatus.DELETED);
}
@Override
public Page<User> listUsers(UserStatus status, Pageable pageable) {
if (status != null) {
return userRepository.findByStatus(status, pageable);
}
return userRepository.findAll(pageable);
}
// 事件类定义
@Getter
@AllArgsConstructor
public static class UserRegisteredEvent {
private final User user;
}
@Getter
@AllArgsConstructor
public static class UserDeletedEvent {
private final User user;
}
}
这个用户服务实现包含了完整的安全特性:
| 安全特性 | 实现方式 | 作用 |
|---|---|---|
| 限流防护 | RateLimiter | 防止暴力注册 |
| 密码加密 | BCryptPasswordEncoder | 存储安全 |
| 账户锁定 | 失败尝试计数 | 防止暴力破解 |
| 输入验证 | Bean Validation + 自定义验证 | 数据完整性 |
| 唯一性检查 | 数据库约束 + 业务逻辑 | 防止重复注册 |
| 审计日志 | 关键操作记录 | 安全审计 |
| 事件驱动 | Spring事件机制 | 解耦业务逻辑 |
| 缓存优化 | Spring Cache | 性能提升 |
4.3 数据访问层优化
使用Spring Data JPA时,我习惯添加一些自定义查询方法:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Optional<User> findByEmail(String email);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
boolean existsByPhone(String phone);
Page<User> findByStatus(UserStatus status, Pageable pageable);
@Query("SELECT u FROM User u WHERE u.status != 'DELETED' AND " +
"(u.username LIKE %:keyword% OR u.email LIKE %:keyword%)")
Page<User> searchUsers(@Param("keyword") String keyword, Pageable pageable);
@Modifying
@Query("UPDATE User u SET u.status = 'INACTIVE' WHERE u.lastLoginAt < :threshold")
int deactivateInactiveUsers(@Param("threshold") LocalDateTime threshold);
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT u FROM User u WHERE u.id = :id")
Optional<User> findByIdForUpdate(@Param("id") Long id);
}
这些自定义方法让业务代码更简洁,同时通过@Lock注解实现了悲观锁,在处理账户余额等敏感操作时特别有用。
5. 系统集成与生产部署
5.1 完整的控制器实现
将AI能力通过REST API暴露出来:
@RestController
@RequestMapping("/api/v1/ai")
@Validated
@Slf4j
public class AiCustomerController {
private final ChatClient chatClient;
private final MeterRegistry meterRegistry;
public AiCustomerController(ChatClient chatClient, MeterRegistry meterRegistry) {
this.chatClient = chatClient;
this.meterRegistry = meterRegistry;
}
@PostMapping("/chat")
@Operation(summary = "AI对话接口", description = "与智能客服进行对话")
public ResponseEntity<AiResponse> chat(
@RequestBody @Valid ChatRequest request,
@RequestHeader(value = "X-Session-Id", required = false) String sessionId) {
Timer.Sample sample = Timer.start(meterRegistry);
try {
log.debug("收到AI对话请求:session={}, message={}",
sessionId, request.getMessage());
String response = chatClient.prompt()
.user(request.getMessage())
.call()
.content();
AiResponse aiResponse = AiResponse.success(response);
// 记录指标
sample.stop(meterRegistry.timer("ai.chat.duration",
"model", "ollama",
"success", "true"));
meterRegistry.counter("ai.chat.requests.total").increment();
return ResponseEntity.ok(aiResponse);
} catch (Exception e) {
log.error("AI对话处理失败", e);
sample.stop(meterRegistry.timer("ai.chat.duration",
"model", "ollama",
"success", "false"));
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(AiResponse.error("AI服务暂时不可用"));
}
}
@PostMapping("/chat/stream")
@Operation(summary = "流式AI对话", description = "支持流式响应的AI对话")
public Flux<ServerSentEvent<String>> streamChat(
@RequestBody @Valid ChatRequest request,
@RequestHeader(value = "X-Session-Id", required = false) String sessionId) {
log.debug("收到流式AI对话请求:session={}", sessionId);
return chatClient.prompt()
.user(request.getMessage())
.stream()
.content()
.map(content -> ServerSentEvent.builder(content).build())
.doOnSubscribe(subscription -> {
meterRegistry.counter("ai.chat.stream.requests.total").increment();
})
.doOnError(error -> {
log.error("流式对话失败", error);
meterRegistry.counter("ai.chat.stream.errors.total").increment();
});
}
@GetMapping("/tools")
@Operation(summary = "获取可用工具列表", description = "查询AI客服支持的工具")
public ResponseEntity<List<ToolInfo>> getAvailableTools() {
// 这里可以动态返回系统支持的工具列表
List<ToolInfo> tools = List.of(
ToolInfo.builder()
.name("query_weather")
.description("查询城市天气")
.parameters(List.of(
new ToolParameter("city", "string", "城市名称", true),
new ToolParameter("include_forecast", "boolean", "包含预报", false)
))
.build(),
ToolInfo.builder()
.name("register_user")
.description("注册新用户")
.parameters(List.of(
new ToolParameter("username", "string", "用户名", true),
new ToolParameter("password", "string", "密码", true),
new ToolParameter("email", "string", "邮箱", false)
))
.build()
);
return ResponseEntity.ok(tools);
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ToolInfo {
private String name;
private String description;
private List<ToolParameter> parameters;
}
@Data
@AllArgsConstructor
public static class ToolParameter {
private String name;
private String type;
private String description;
private boolean required;
}
}
这个控制器提供了完整的API接口,包括:
- 同步对话:普通的请求-响应模式
- 流式对话:支持实时流式响应
- 工具发现:让前端知道AI支持哪些功能
- 监控集成:自动记录性能指标
5.2 生产环境配置
生产环境的配置需要更多考虑:
# application-prod.yml
spring:
profiles: prod
datasource:
url: jdbc:mysql://${DB_HOST:localhost}:3306/${DB_NAME:ai_customer}?useSSL=false&allowPublicKeyRetrieval=true
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
# Redis缓存配置
data:
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
password: ${REDIS_PASSWORD:}
database: 0
timeout: 2000ms
lettuce:
pool:
max-active: 20
max-idle: 10
min-idle: 5
# 监控端点
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheus
endpoint:
health:
show-details: always
metrics:
export:
prometheus:
enabled: true
tracing:
sampling:
probability: 0.1 # 10%的请求采样
# 日志配置
logging:
level:
org.springframework: INFO
com.example: DEBUG
file:
name: logs/ai-customer-service.log
max-size: 10MB
max-history: 30
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
# 安全配置
security:
cors:
allowed-origins: ${ALLOWED_ORIGINS:http://localhost:3000}
allowed-methods: GET,POST,PUT,DELETE,OPTIONS
allowed-headers: "*"
allow-credentials: true
# 业务配置
customer-service:
rate-limit:
enabled: true
global:
requests-per-minute: 1000
per-ip:
requests-per-minute: 60
per-user:
requests-per-minute: 30
cache:
weather-ttl: 300 # 5分钟
user-ttl: 3600 # 1小时
monitoring:
enabled: true
metrics-prefix: ai.customer
trace-sampling-rate: 0.1
5.3 Docker部署配置
# 使用多阶段构建减小镜像体积
FROM eclipse-temurin:17-jdk-alpine as builder
WORKDIR /app
COPY mvnw .
COPY .mvn .mvn
COPY pom.xml .
RUN ./mvnw dependency:go-offline -B
COPY src src
RUN ./mvnw package -DskipTests
# 运行时镜像
FROM eclipse-temurin:17-jre-alpine
WORKDIR /app
# 安装必要的工具
RUN apk add --no-cache curl bash
# 创建非root用户
RUN addgroup -S spring && adduser -S spring -G spring
USER spring:spring
# 复制构建产物
COPY --from=builder /app/target/*.jar app.jar
# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=60s --retries=3 \
CMD curl -f http://localhost:8080/actuator/health || exit 1
# 环境变量
ENV JAVA_OPTS="-Xmx512m -Xms256m -XX:+UseG1GC -XX:MaxGCPauseMillis=200"
ENV SPRING_PROFILES_ACTIVE=prod
# 暴露端口
EXPOSE 8080
# 启动命令
ENTRYPOINT ["sh", "-c", "java ${JAVA_OPTS} -jar /app/app.jar"]
对应的docker-compose.yml:
version: '3.8'
services:
ai-customer-service:
build: .
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=prod
- DB_HOST=mysql
- DB_USERNAME=${DB_USERNAME}
- DB_PASSWORD=${DB_PASSWORD}
- REDIS_HOST=redis
- DASHSCOPE_API_KEY=${DASHSCOPE_API_KEY}
- WEATHER_API_KEY=${WEATHER_API_KEY}
depends_on:
mysql:
condition: service_healthy
redis:
condition: service_healthy
ollama:
condition: service_started
networks:
- ai-network
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/actuator/health"]
interval: 30s
timeout: 10s
retries: 3
mysql:
image: mysql:8.0
environment:
- MYSQL_ROOT_PASSWORD=${DB_ROOT_PASSWORD}
- MYSQL_DATABASE=ai_customer
- MYSQL_USER=${DB_USERNAME}
- MYSQL_PASSWORD=${DB_PASSWORD}
ports:
- "3306:3306"
volumes:
- mysql-data:/var/lib/mysql
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
networks:
- ai-network
restart: unless-stopped
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis-data:/data
networks:
- ai-network
restart: unless-stopped
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 3
ollama:
image: ollama/ollama:latest
ports:
- "11434:11434"
volumes:
- ollama-data:/root/.ollama
networks:
- ai-network
restart: unless-stopped
command: serve
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus-data:/prometheus
networks:
- ai-network
restart: unless-stopped
grafana:
image: grafana/grafana:latest
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
volumes:
- grafana-data:/var/lib/grafana
- ./grafana/provisioning:/etc/grafana/provisioning
networks:
- ai-network
restart: unless-stopped
depends_on:
- prometheus
volumes:
mysql-data:
redis-data:
ollama-data:
prometheus-data:
grafana-data:
networks:
ai-network:
driver: bridge
这个完整的Docker Compose配置包含了所有必要的服务,并且配置了健康检查、数据持久化和监控系统。
5.4 监控与告警配置
prometheus.yml配置:
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'ai-customer-service'
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['ai-customer-service:8080']
labels:
application: 'ai-customer-service'
environment: 'production'
- job_name: 'mysql'
static_configs:
- targets: ['mysql:9104']
metrics_path: /metrics
- job_name: 'redis'
static_configs:
- targets: ['redis:9121']
alerting:
alertmanagers:
- static_configs:
- targets: ['alertmanager:9093']
rule_files:
- "alerts.yml"
对应的告警规则alerts.yml:
groups:
- name: ai-customer-alerts
rules:
- alert: HighErrorRate
expr: rate(http_server_requests_errors_total[5m]) > 0.05
for: 2m
labels:
severity: warning
annotations:
summary: "高错误率检测"
description: "错误率超过5%,当前值 {{ $value }}"
- alert: HighResponseTime
expr: histogram_quantile(0.95, rate(http_server_requests_duration_seconds_bucket[5m])) > 2
for: 5m
labels:
severity: warning
annotations:
summary: "高响应时间"
description: "95%分位响应时间超过2秒,当前值 {{ $value }}s"
- alert: ServiceDown
expr: up{job="ai-customer-service"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: "服务不可用"
description: "AI客服服务已下线"
- alert: HighMemoryUsage
expr: process_resident_memory_bytes / process_memory_max_bytes > 0.8
for: 5m
labels:
severity: warning
annotations:
summary: "高内存使用率"
description: "内存使用率超过80%,当前值 {{ $value }}%"
这套监控配置可以确保系统在出现问题时及时告警,便于快速响应。
我在实际部署这个系统时发现,最大的挑战不是技术实现,而是如何平衡功能、性能和成本。通过使用Ollama本地模型,我们每月可以节省数千元的API调用费用;通过合理的缓存策略,天气查询的响应时间从秒级降低到毫秒级;通过多层安全防护,系统运行半年多来没有发生一起安全事件。
最让我满意的是这个系统的扩展性。当我们需要增加新的AI能力时,只需要添加一个新的@Tool注解方法;当流量增长时,通过简单的配置调整就能应对。这种"最小可行产品"的思路,让团队能够快速验证想法,同时为未来的扩展留足了空间。
183



被折叠的 条评论
为什么被折叠?



