在Java中实现在线留言(关注)、点赞、获取在线人数等功能

本文详细介绍了如何在Java中,利用SpringBoot和MySQL实现在线留意、关注功能以及点赞功能,并通过HttpSessionListener监控在线人数。涉及实体类设计、Repository操作、服务层业务逻辑和控制器的HTTP请求处理。
摘要由CSDN通过智能技术生成

在Java中实现在线留意(关注)、点赞、获取在线人数等功能,通常需要结合Web框架(如Spring Boot或Java Servlets)和数据库(如MySQL)来实现。下面是一个基于Spring Boot的简要示例:

  1. 用户在线状态管理
    • 为了获取在线人数,可以使用HttpSessionListener监听会话创建与销毁事件,维护一个在线用户计数器。
    • 创建一个OnlineUserCounter类实现HttpSessionListener接口:
public class OnlineUserCounter implements HttpSessionListener {
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        onlineCount.incrementAndGet();
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        onlineCount.decrementAndGet();
    }

    public int getOnlineCount() {
        return onlineCount.get();
    }
}
  • 在Spring Boot的配置文件中注册该监听器。
  1. 关注功能
    • 定义一个Follow实体类表示关注关系,并通过Repository操作数据库记录关注状态。
@Entity
@Table(name = "followers")
public class Follow {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private User follower; // 关注者

    @ManyToOne
    private User following; // 被关注者

    // 构造函数、getter和setter...
}

@Repository
public interface FollowRepository extends JpaRepository<Follow, Long> {
    boolean existsByFollowerAndFollowing(User follower, User following);
    // 其他查询方法...
}
  1. 点赞功能
    • 定义一个Like实体类表示点赞行为,并通过Repository操作数据库记录点赞信息。
@Entity
@Table(name = "likes")
public class Like {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private User liker; // 点赞者

    @ManyToOne
    private Post post; // 被点赞的内容(这里以帖子为例)

    // 构造函数、getter和setter...
}

@Repository
public interface LikeRepository extends JpaRepository<Like, Long> {
    long countByPost(Post post); // 获取某内容的点赞数量
    // 其他查询方法...
}
  1. 服务层处理业务逻辑
    • 创建服务类处理用户的关注、点赞操作以及获取在线人数。
@Service
public class UserService {
    @Autowired
    private FollowRepository followRepository;
    @Autowired
    private LikeRepository likeRepository;
    @Autowired
    private OnlineUserCounter onlineUserCounter;

    public void follow(User follower, User following) {
        if (!followRepository.existsByFollowerAndFollowing(follower, following)) {
            Follow follow = new Follow(follower, following);
            followRepository.save(follow);
        }
    }

    public void like(User liker, Post post) {
        Like like = new Like(liker, post);
        likeRepository.save(like);
    }

    public int getOnlineCount() {
        return onlineUserCounter.getOnlineCount();
    }
}
  1. 控制器处理HTTP请求
    • 创建控制器类处理前端发起的关注、点赞请求以及获取在线人数API调用。
@RestController
@RequestMapping("/api")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/follow/{followingId}")
    public ResponseEntity<?> follow(@PathVariable("followingId") Long followingId, Principal principal) {
        // 从Principal中获取当前登录用户信息
        User follower = ...; // 根据principal解析出用户
        User following = userRepository.findById(followingId).orElseThrow(() -> new ResourceNotFoundException("User not found"));

        userService.follow(follower, following);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/like/post/{postId}")
    public ResponseEntity<?> likePost(@PathVariable("postId") Long postId, Principal principal) {
        // 同样获取当前登录用户
        User liker = ...;
        Post post = postRepository.findById(postId).orElseThrow(() -> new ResourceNotFoundException("Post not found"));

        userService.like(liker, post);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/online-count")
    public ResponseEntity<Integer> getOnlineCount() {
        return ResponseEntity.ok(userService.getOnlineCount());
    }
}

请注意,上述代码仅为简化版示例,实际应用中还需要考虑事务处理、权限验证等问题。同时,对于高并发场景下的点赞计数,推荐使用无锁数据结构如AtomicLong或者数据库提供的原子更新操作等方式进行优化。

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值