ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

基于SpringBoot的家庭食谱分享与食材采购推荐系统设计与实现

基于SpringBoot的家庭食谱分享与食材采购推荐系统设计与实现 一、 项目背景与意义在快节奏的现代生活中家庭烹饪面临着“吃什么”、“怎么吃”、“如何买”三大核心痛点。传统的食谱应用与生鲜电商平台相互割裂用户需要反复切换应用体验碎片化。同时个性化推荐能力的缺失使得用户难以高效获取符合自身口味、营养需求和预算的烹饪方案。因此构建一个集食谱分享、智能推荐与食材采购于一体的综合性平台具有重要的现实意义提升生活效率一站式解决从灵感获取到食材到家的全流程降低决策与采购成本。促进健康饮食通过营养分析与个性化推荐引导用户形成更科学、均衡的饮食习惯。构建社区生态连接美食爱好者形成内容创作、分享与互动的良性循环沉淀用户价值。技术实践价值作为全栈项目它涵盖了微服务、推荐算法、前后端分离等现代Web开发核心技术栈是学习与实践的优质案例。二、 技术栈选型本项目采用前后端分离架构以下是核心的技术栈构成2.1 后端技术栈 (SpringBoot)核心框架Spring Boot 2.7 提供快速启动和自动配置。Web层Spring MVC 处理RESTful API请求。数据持久层ORMMyBatis-Plus 简化CRUD操作。数据库MySQL 8.0 存储核心业务数据用户、食谱、订单等。缓存Redis 用于会话管理、热点数据缓存及推荐结果暂存。安全与认证Spring Security JWT (JSON Web Token) 实现安全的用户认证与授权。搜索服务Elasticsearch 提供食谱全文检索、食材模糊匹配等高阶搜索能力。消息队列RabbitMQ 异步处理如订单生成、推荐计算、通知发送等耗时任务提升系统响应能力。推荐引擎基于Python的Flask轻量级服务集成协同过滤、内容推荐等算法通过REST接口与Java主服务交互。2.2 前端技术栈前端框架Vue 3 Composition API 构建响应式用户界面。UI组件库Element Plus 提供丰富的桌面端组件。状态管理Pinia 替代Vuex进行集中式状态管理。构建工具Vite 实现极速的开发服务器启动和热更新。移动端适配使用Vant或Uni-app框架开发小程序或H5版本覆盖多端场景。2.3 运维与部署容器化Docker Docker Compose 实现环境一致性与快速部署。持续集成/部署Jenkins或GitLab CI 自动化构建、测试与发布流程。API文档Knife4j (Swagger增强) 自动生成并管理后端API接口文档。三、 系统核心功能模块与代码示例3.1 用户服务与JWT认证负责用户注册、登录、信息管理及鉴权。// JWT工具类示例 Component public class JwtUtil { private static final String SECRET_KEY your-secret-key; private static final long EXPIRATION 86400000L; // 24小时 public String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() EXPIRATION)) .signWith(SignatureAlgorithm.HS512, SECRET_KEY) .compact(); } public String getUsernameFromToken(String token) { return Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody() .getSubject(); } } // Spring Security配置类核心片段 Configuration EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers(/api/auth/**, /api/recipes/public).permitAll() // 公开接口 .anyRequest().authenticated() // 其他接口需认证 .and() .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } }3.2 食谱服务 (Recipe Service)核心实体与业务逻辑包含食谱的增删改查、收藏、点赞等。// 食谱实体类 (使用Lombok简化) Data TableName(recipe) public class Recipe { TableId(type IdType.AUTO) private Long id; private String title; private String description; private String coverImage; private Long authorId; private Integer difficulty; // 难度等级 private Integer prepTime; // 准备时间(分钟) private Integer cookTime; // 烹饪时间(分钟) TableField(typeHandler JacksonTypeHandler.class) private ListString tags; // 标签JSON存储 TableField(typeHandler JacksonTypeHandler.class) private ListIngredient ingredients; // 食材清单 TableField(typeHandler JacksonTypeHandler.class) private ListCookingStep steps; // 烹饪步骤 private Integer viewCount; private Integer likeCount; private Integer collectCount; private LocalDateTime createTime; private LocalDateTime updateTime; } // 服务层核心方法示例 Service public class RecipeService { Autowired private RecipeMapper recipeMapper; Autowired private RedisTemplateString, Object redisTemplate; public Pagelt;RecipeVOgt; getRecipesByPage(Pagelt;Recipegt; page, RecipeQueryDTO queryDTO) { LambdaQueryWrapperlt;Recipegt; wrapper new LambdaQueryWrapperlt;gt;(); // 构建动态查询条件 if (StringUtils.isNotBlank(queryDTO.getKeyword())) { wrapper.like(Recipe::getTitle, queryDTO.getKeyword()) .or().like(Recipe::getDescription, queryDTO.getKeyword()); } if (queryDTO.getDifficulty() ! null) { wrapper.eq(Recipe::getDifficulty, queryDTO.getDifficulty()); } // 执行分页查询 Pagelt;Recipegt; recipePage recipeMapper.selectPage(page, wrapper); // 转换为VO并返回 return recipePage.convert(this::convertToVO); } Cacheable(value recipe, key #id) public RecipeVO getRecipeDetail(Long id) { Recipe recipe recipeMapper.selectById(id); if (recipe null) { throw new BusinessException(食谱不存在); } // 异步增加浏览量 CompletableFuture.runAsync(() - { recipeMapper.incrementViewCount(id); // 更新Redis中的热门食谱排行榜 redisTemplate.opsForZSet().incrementScore(hot:recipes, id.toString(), 1); }); return convertToVO(recipe); } }3.3 推荐服务 (Recommendation Service)提供个性化食谱推荐与食材采购建议。// 推荐服务接口定义 public interface RecommendationService { /** * 为用户推荐食谱 * param userId 用户ID * param topN 返回数量 * return 推荐食谱ID列表 */ ListLong recommendRecipes(Long userId, int topN); /** * 根据已选食谱生成智能采购清单 * param recipeIds 食谱ID列表 * return 合并去重后的食材清单 */ Listlt;Ingredientgt; generateShoppingList(Listlt;Longgt; recipeIds); } // 基于协同过滤的推荐服务实现 (伪代码逻辑) Service public class CollaborativeFilteringService implements RecommendationService { Autowired private UserBehaviorRepository behaviorRepo; Autowired private RecipeClient recipeClient; // 调用食谱服务 Override public Listlt;Longgt; recommendRecipes(Long userId, int topN) { // 1. 获取目标用户的交互行为浏览、收藏、点赞 Listlt;UserBehaviorgt; userBehaviors behaviorRepo.findByUserId(userId); if (userBehaviors.isEmpty()) { // 冷启动返回热门食谱 return getHotRecipes(topN); } // 2. 找到相似用户基于行为向量计算余弦相似度 Listamp;lt;Longamp;gt; similarUserIds findSimilarUsers(userId, userBehaviors); // 3. 从相似用户喜欢的食谱中过滤掉目标用户已交互的进行排序 Listamp;lt;Longamp;gt; candidateRecipeIds collectRecipesFromSimilarUsers(similarUserIds, userId); // 4. 返回TopN return candidateRecipeIds.stream().limit(topN).collect(Collectors.toList()); } private Listlt;Longgt; getHotRecipes(int topN) { // 从Redis ZSet中获取热门食谱ID Setlt;Objectgt; hotIds redisTemplate.opsForZSet().reverseRange(hot:recipes, 0, topN - 1); return hotIds.stream().map(id - Long.parseLong(id.toString())).collect(Collectors.toList()); } }3.4 订单与采购服务处理用户基于推荐清单生成的食材采购订单。// 使用RabbitMQ异步处理订单创建 Service public class OrderService { Autowired private RabbitTemplate rabbitTemplate; public void createOrderFromShoppingCart(Long userId, Listlt;CartItemDTOgt; cartItems) { // 1. 订单基础信息落库 Order order buildOrder(userId, cartItems); orderMapper.insert(order); // 2. 发送异步消息处理库存扣减、推荐模型更新等后续任务 OrderMessage message new OrderMessage(order.getId(), userId, cartItems); rabbitTemplate.convertAndSend(order.exchange, order.create, message); // 3. 立即返回订单ID前端可轮询查询状态 // ... } } // 消息消费者更新用户行为用于改进推荐 Component RabbitListener(queues order.process.queue) public class OrderProcessConsumer { RabbitHandler public void processOrderMessage(OrderMessage message) { // 记录用户购买行为丰富用户画像 userBehaviorService.recordPurchase(message.getUserId(), message.getRecipeIds()); // 触发推荐模型的增量更新 recommendationModelService.triggerUpdate(message.getUserId()); } }四、 总结与展望本系统通过整合SpringBoot后端生态与Vue前端技术构建了一个功能完整的家庭食谱分享与智能采购平台。其核心价值在于打破了食谱与电商的数据孤岛利用推荐算法实现了“人-内容-商品”的精准连接。未来可扩展方向算法深化引入深度学习模型进行图像识别根据菜品图片推荐食谱和时序预测根据季节、节假日推荐食谱。多端融合开发微信小程序、APP并接入智能音箱实现语音搜索与播报食谱。供应链整合直接对接生鲜供应商API实现一键比价、定时送达等更深入的采购体验。社区运营增加视频菜谱、直播教学、厨艺挑战赛等UGC功能提升用户粘性。该项目不仅是一个实用的生活工具也是一个涵盖了微服务设计、大数据处理、算法集成和高并发应对的综合性全栈学习案例具有较高的实践与参考价值。
返回列表