登录
首页 >  文章 >  java教程

Java实现问答点赞与回复功能详解

时间:2025-10-30 08:26:30 205浏览 收藏

大家好,今天本人给大家带来文章《Java实现在线问答点赞与回复方法》,文中内容主要涉及到,如果你对文章方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

首先设计Question、Reply和Like实体类,接着通过LikeService实现点赞去重与计数更新,ReplyService处理回复存储与查询,最后由QuestionController暴露reply和like接口,结合数据库与缓存优化性能,确保点赞功能的正确性与高效性。

在Java中如何实现在线问答的点赞与回复

在Java中实现在线问答系统的点赞与回复功能,核心在于设计合理的数据模型、服务逻辑以及接口交互。以下是具体实现思路和关键代码示例。

1. 数据模型设计

定义问题、回复、点赞相关的实体类。

Question(问题):

public class Question {
    private Long id;
    private String title;
    private String content;
    private Long userId;
    private List<Reply> replies = new ArrayList<>();
    private int likeCount = 0;
    // getter 和 setter
}

Reply(回复):

public class Reply {
    private Long id;
    private Long questionId;
    private Long userId;
    private String content;
    private int likeCount = 0;
    // getter 和 setter
}

Like(点赞记录):用于防止重复点赞

public class Like {
    private Long id;
    private Long targetId;   // 目标ID(问题或回复)
    private String targetType; // 类型:"question" 或 "reply"
    private Long userId;
    // getter 和 setter
}

2. 点赞功能实现

通过判断目标类型(问题或回复),检查用户是否已点赞,未点赞则添加记录并更新计数。

@Service
public class LikeService {

    private Map<String, Set<Long>> userLikes = new HashMap<>(); // 实际应使用数据库

    public boolean addLike(Long userId, String targetType, Long targetId) {
        String key = targetType + ":" + targetId;
        Set<Long> likedUsers = userLikes.computeIfAbsent(key, k -> new HashSet<>());

        if (likedUsers.contains(userId)) {
            return false; // 已点赞
        }

        likedUsers.add(userId);

        // 更新问题或回复的点赞数(实际中调用对应service)
        if ("question".equals(targetType)) {
            updateQuestionLikeCount(targetId, 1);
        } else if ("reply".equals(targetType)) {
            updateReplyLikeCount(targetId, 1);
        }
        return true;
    }

    private void updateQuestionLikeCount(Long questionId, int delta) {
        // 调用 QuestionService 增加点赞数
    }

    private void updateReplyLikeCount(Long replyId, int delta) {
        // 调用 ReplyService 增加点赞数
    }
}

3. 回复功能实现

用户提交回复后,将内容保存并与对应问题关联。

@Service
public class ReplyService {

    private List<Reply> replies = new ArrayList<>(); // 模拟存储

    public Reply createReply(Long questionId, Long userId, String content) {
        Reply reply = new Reply();
        reply.setId((long) (replies.size() + 1));
        reply.setQuestionId(questionId);
        reply.setUserId(userId);
        reply.setContent(content);
        replies.add(reply);
        return reply;
    }

    public List<Reply> getRepliesByQuestionId(Long questionId) {
        return replies.stream()
                .filter(r -> r.getQuestionId().equals(questionId))
                .collect(Collectors.toList());
    }
}

4. 控制器层接口

提供HTTP接口供前端调用。

@RestController
@RequestMapping("/api/questions")
public class QuestionController {

    @Autowired
    private ReplyService replyService;

    @Autowired
    private LikeService likeService;

    @PostMapping("/{id}/reply")
    public Reply replyToQuestion(
        @PathVariable Long id,
        @RequestParam Long userId,
        @RequestParam String content) {
        return replyService.createReply(id, userId, content);
    }

    @PostMapping("/{id}/like")
    public ResponseEntity<String> likeQuestion(
        @PathVariable Long id,
        @RequestParam Long userId) {
        boolean success = likeService.addLike(userId, "question", id);
        if (success) {
            return ResponseEntity.ok("点赞成功");
        } else {
            return ResponseEntity.badRequest().body("已点赞");
        }
    }

    @PostMapping("/replies/{replyId}/like")
    public ResponseEntity<String> likeReply(
        @PathVariable Long replyId,
        @RequestParam Long userId) {
        boolean success = likeService.addLike(userId, "reply", replyId);
        if (success) {
            return ResponseEntity.ok("点赞成功");
        } else {
            return ResponseEntity.badRequest().body("已点赞");
        }
    }
}

基本上就这些。使用Spring Boot可快速搭建该结构,实际项目中需结合数据库(如MySQL、MongoDB)和缓存(如Redis)提升性能。点赞去重建议用唯一索引约束,避免并发问题。

以上就是《Java实现问答点赞与回复功能详解》的详细内容,更多关于的资料请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>