refactor(mcwl): 重构代码并添加新功能

- 修改了 AddBenefitNameDto 和 EditBenefitNameDto 中的注解- 添加了 AdviceConstant 类用于定义通知类型常量
- 在 BenefitController 中添加了根据权益名称 ID 查询权益的接口
- 在 CommunityServiceImpl 中实现了社区通知的发送- 移除了与 MQTT 相关的代码和接口
master
yang 2025-04-14 15:30:45 +08:00
parent a74e6412e0
commit 1f85f77ca3
44 changed files with 641 additions and 1171 deletions

View File

@ -0,0 +1,31 @@
package com.mcwl.web.controller.communityCenter;
import com.mcwl.common.core.domain.R;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
*
*/
@Api(tags = "个人主页")
@RestController
@RequiredArgsConstructor
@RequestMapping("personHome")
public class PersonHomeController {
/**
*
*/
@RequestMapping("list")
public R<Object> list(){
return R.ok();
}
}

View File

@ -1,28 +0,0 @@
package com.mcwl.web.controller.communityCenter;
import com.mcwl.common.core.controller.BaseController;
import com.mcwl.communityCenter.service.PublishCommentLikeService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @AuthorChenYan
* @Projectmcwl-ai
* @Packagecom.mcwl.web.controller.communityCenter
* @FilenamePublishCommissionLikeController
* @Description TODO
* @Date2025/1/17 14:21
*/
@Api(tags = "社群评论区点赞")
@RestController
@RequestMapping("PublishCommissionLike")
public class PublishCommentLikeController extends BaseController {
@Autowired
private PublishCommentLikeService publishCommentLikeService;
}

View File

@ -0,0 +1,42 @@
package com.mcwl.web.controller.communityCenter;
import com.mcwl.common.core.controller.BaseController;
import com.mcwl.common.core.domain.R;
import com.mcwl.communityCenter.domain.dto.PublishCommentLikeRes;
import com.mcwl.communityCenter.domain.dto.PublishLikeRes;
import com.mcwl.communityCenter.service.PublishCommentLikeService;
import com.mcwl.communityCenter.service.PublishLikeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
/**
*
*/
@Api(tags = "社群发布点赞")
@RestController
@RequiredArgsConstructor
@RequestMapping("PublishLike")
public class PublishLikeController extends BaseController {
private final PublishLikeService publishLikeService;
/**
* /
*/
@PostMapping("/like")
@ApiOperation(value = "点赞/取消点赞")
public R<Object> like(@RequestBody @Valid PublishLikeRes publishLikeRes) {
publishLikeService.like(publishLikeRes);
return R.ok();
}
}

View File

@ -6,6 +6,7 @@ import com.mcwl.memberCenter.domain.Benefit;
import com.mcwl.memberCenter.domain.dto.AddBenefitDto;
import com.mcwl.memberCenter.domain.dto.EditBenefitDto;
import com.mcwl.memberCenter.domain.vo.BenefitVo;
import com.mcwl.memberCenter.enums.MemberBenefitTypeEnum;
import com.mcwl.memberCenter.service.BenefitService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -52,6 +53,19 @@ public class BenefitController {
return R.ok();
}
/**
* id
*/
@ApiOperation(value = "根据权益名称id查询权益")
@GetMapping("getBenefitByBenefitId")
public R<List<Benefit>> getBenefitByBenefitId(@NotNull(message = "权益名称id不能为空") Long benefitNameId) {
List<Benefit> benefitList = benefitService.lambdaQuery()
.eq(Benefit::getBenefitNameId, benefitNameId)
.list();
return R.ok(benefitList);
}
/**
*
*/

View File

@ -1,26 +0,0 @@
package com.mcwl.web.controller.mqtt;
import com.mcwl.common.core.domain.R;
import com.mcwl.myInvitation.domain.vo.CommissionRatioVo;
import com.mcwl.resource.util.MqttTemplate;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController()
@RequiredArgsConstructor
@RequestMapping("/mqtt")
public class MqttController {
private final MqttTemplate mqttTemplate;
@GetMapping("/send")
public void list(String topic, String msg) {
mqttTemplate.publish(topic, msg);
}
}

View File

@ -174,13 +174,6 @@ huawei:
upload:
endPoint: obs.cn-south-1.myhuaweicloud.com
mqtt:
broker-url: tcp://113.45.190.154:1883
client-id-prefix: emqx-client
connection-timeout: 30
keep-alive-interval: 60
max-reconnect-attempts: 5
clean-session: true
#用户头像与背景
mcwl:

View File

@ -161,11 +161,3 @@ huawei:
upload:
endPoint: obs.cn-south-1.myhuaweicloud.com
mqtt:
broker-url: tcp://192.168.136.128:1883
client-id-prefix: emqx-client
connection-timeout: 30
keep-alive-interval: 60
max-reconnect-attempts: 5
clean-session: true

View File

@ -0,0 +1,29 @@
package com.mcwl.communityCenter.constant;
/**
*
*/
public class AdviceConstant {
/**
*
*/
public static final int COMMUNITY_NOTICE = 0;
/**
*
*/
public static final int REPLY_ME = 1;
/**
*
*/
public static final int WAIT_ME_ANSWER = 2;
/**
*
*/
public static final int LIKE = 3;
}

View File

@ -28,6 +28,14 @@ public class CommunityAdvice extends BaseEntity {
* id
*/
private Long communityId;
/**
*
*/
private Long sendUserId;
/**
* 0 1 2 3
*/
private Integer adviceType;
/**
*
*/

View File

@ -29,18 +29,29 @@ public class PublishCommentLike extends BaseEntity {
@ApiModelProperty(value = "评论点赞id")
private Long id;
/**
* id
* id
*/
@ApiModelProperty(value = "户id")
private Long userId;
@ApiModelProperty(value = "户id")
private Long tenantId;
/**
* id
*/
@ApiModelProperty(value = "社群id")
private Long communityId;
/**
* id
*/
@ApiModelProperty(value = "发布id")
private Long publishId;
/**
* id
*/
@ApiModelProperty(value = "评论id")
private Long publishCommentId;
/**
* id
*/
@ApiModelProperty(value = "用户id")
private Long userId;
}

View File

@ -0,0 +1,49 @@
package com.mcwl.communityCenter.domain;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.mcwl.common.core.domain.BaseEntity;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Builder
@TableName("cc_publish_like")
public class PublishLike extends BaseEntity {
@TableId
private Long id;
/**
* id - id
*/
@TableField(fill = FieldFill.INSERT)
private Long tenantId;
/**
* id
*/
private Long communityId;
/**
* id
*/
private Long publishId;
/**
* id
*/
private Long userId;
}

View File

@ -0,0 +1,44 @@
package com.mcwl.communityCenter.domain.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* /
*/
@Data
@ApiModel(value = "点赞/取消点赞请求参数")
public class PublishCommentLikeRes {
/**
* id
*/
@ApiModelProperty(value = "用户id", required = true)
@NotNull(message = "用户id不能为空")
private Long tenantId;
/**
* id
*/
@ApiModelProperty(value = "社区id", required = true)
@NotNull(message = "社区id不能为空")
private Long communityId;
/**
* id
*/
@ApiModelProperty(value = "发布id", required = true)
@NotNull(message = "发布id不能为空")
private Long publishId;
/**
* id
*/
@ApiModelProperty(value = "评论id", required = true)
@NotNull(message = "评论id不能为空")
private Long commentId;
}

View File

@ -0,0 +1,36 @@
package com.mcwl.communityCenter.domain.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* /
*/
@Data
@ApiModel(value = "点赞/取消点赞请求参数")
public class PublishLikeRes {
/**
* id
*/
@ApiModelProperty(value = "用户id", required = true)
@NotNull(message = "用户id不能为空")
private Long tenantId;
/**
* id
*/
@ApiModelProperty(value = "社区id", required = true)
@NotNull(message = "社区id不能为空")
private Long communityId;
/**
* id
*/
@ApiModelProperty(value = "发布id", required = true)
@NotNull(message = "发布id不能为空")
private Long publishId;
}

View File

@ -29,6 +29,13 @@ public class QuestionRes {
@ApiModelProperty(value = "社区ID", required = true, position = 1)
private Long communityId;
/**
*
*/
@NotNull(message = "提问用户id不能为空")
@ApiModelProperty(value = "提问用户id", required = true, position = 2)
private Long questionUserId;
/**
*
*/

View File

@ -1,8 +1,13 @@
package com.mcwl.communityCenter.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mcwl.communityCenter.domain.PublishCommentLike;
import com.mcwl.communityCenter.domain.dto.PublishCommentLikeRes;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import javax.validation.constraints.NotNull;
/**
* @AuthorChenYan
@ -14,4 +19,16 @@ import org.apache.ibatis.annotations.Mapper;
*/
@Mapper
public interface PublishCommentLikeMapper extends BaseMapper<PublishCommentLike> {
@InterceptorIgnore(tenantLine = "true")
PublishCommentLike selectByTenantIdAndCommunityIdAndCommentId(@Param("tenantId") Long tenantId,
@Param("communityId") Long communityId,
@Param("commentId") Long commentId);
@InterceptorIgnore(tenantLine = "true")
void updateDelFlagById(@Param("publishCommentLike") PublishCommentLike publishCommentLike);
@InterceptorIgnore(tenantLine = "true")
PublishCommentLike selectLike(@Param("publishCommentLikeRes") PublishCommentLikeRes publishCommentLikeRes,
@Param("userId") Long userId);
}

View File

@ -0,0 +1,24 @@
package com.mcwl.communityCenter.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mcwl.communityCenter.domain.PublishCommentLike;
import com.mcwl.communityCenter.domain.PublishLike;
import com.mcwl.communityCenter.domain.dto.PublishCommentLikeRes;
import com.mcwl.communityCenter.domain.dto.PublishLikeRes;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
*
*/
@Mapper
public interface PublishLikeMapper extends BaseMapper<PublishLike> {
@InterceptorIgnore(tenantLine = "true")
PublishLike selectPublishLike(@Param("publishLikeRes") PublishLikeRes publishLikeRes,
@Param("userId") Long userId);
@InterceptorIgnore(tenantLine = "true")
void updateDelFlagById(@Param("publishLike") PublishLike publishLike);
}

View File

@ -2,8 +2,12 @@ package com.mcwl.communityCenter.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mcwl.communityCenter.domain.PublishCommentLike;
import com.mcwl.communityCenter.domain.dto.PublishCommentLikeRes;
import org.springframework.stereotype.Service;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
/**
* @AuthorChenYan
* @Projectmcwl-ai
@ -15,4 +19,5 @@ import org.springframework.stereotype.Service;
@Service
public interface PublishCommentLikeService extends IService<PublishCommentLike> {
void like(PublishCommentLikeRes publishCommentLikeRes);
}

View File

@ -0,0 +1,25 @@
package com.mcwl.communityCenter.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mcwl.communityCenter.domain.PublishCommentLike;
import com.mcwl.communityCenter.domain.PublishLike;
import com.mcwl.communityCenter.domain.dto.PublishCommentLikeRes;
import com.mcwl.communityCenter.domain.dto.PublishLikeRes;
import org.springframework.stereotype.Service;
import javax.validation.Valid;
/**
* @AuthorChenYan
* @Projectmcwl-ai
* @Packagecom.mcwl.communityCenter.service
* @FilenamePublishCommissionLikeService
* @Description TODO
* @Date2025/1/17 14:23
*/
@Service
public interface PublishLikeService extends IService<PublishLike> {
void like(@Valid PublishLikeRes publishLikeRes);
}

View File

@ -14,13 +14,16 @@ import com.mcwl.common.core.redis.RedisCache;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.communityCenter.constant.AdviceConstant;
import com.mcwl.communityCenter.domain.Community;
import com.mcwl.communityCenter.domain.CommunityAdvice;
import com.mcwl.communityCenter.domain.CommunityUser;
import com.mcwl.communityCenter.domain.dto.CommunityListPageRes;
import com.mcwl.communityCenter.domain.dto.CommunityRes;
import com.mcwl.communityCenter.domain.dto.JoinCommunityListPageRes;
import com.mcwl.communityCenter.domain.dto.JoinCommunityRes;
import com.mcwl.communityCenter.domain.vo.CommunityVo;
import com.mcwl.communityCenter.mapper.CommunityAdviceMapper;
import com.mcwl.communityCenter.mapper.CommunityMapper;
import com.mcwl.communityCenter.mapper.CommunityUserMapper;
import com.mcwl.communityCenter.service.CommunityService;
@ -46,6 +49,9 @@ public class CommunityServiceImpl extends ServiceImpl<CommunityMapper, Community
private final RedisCache redisCache;
private final CommunityAdviceMapper communityAdviceMapper;
@Override
public TableDataInfo listByPage(CommunityListPageRes communityListPageRes) {
@ -144,6 +150,19 @@ public class CommunityServiceImpl extends ServiceImpl<CommunityMapper, Community
communityUserMapper.insert(cu);
if (price <= 0) {
return R.ok("加入成功");
}
CommunityAdvice communityAdvice = new CommunityAdvice();
communityAdvice.setTenantId(tenantId);
communityAdvice.setCommunityId(communityId);
communityAdvice.setSendUserId(SecurityUtils.getUserId());
communityAdvice.setAdviceType(AdviceConstant.COMMUNITY_NOTICE);
communityAdvice.setUserId(tenantId);
communityAdvice.setContent(StringUtils.format("{}加入{}社区,金币+{}",
SecurityUtils.getLoginUser().getUser().getNickName(), community.getCommunityName(), price));
communityAdviceMapper.insert(communityAdvice);
return R.ok("加入成功");
}

View File

@ -1,12 +1,27 @@
package com.mcwl.communityCenter.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.communityCenter.constant.AdviceConstant;
import com.mcwl.communityCenter.domain.CommunityAdvice;
import com.mcwl.communityCenter.domain.PublishComment;
import com.mcwl.communityCenter.domain.PublishCommentLike;
import com.mcwl.communityCenter.domain.dto.PublishCommentLikeRes;
import com.mcwl.communityCenter.mapper.PublishCommentLikeMapper;
import com.mcwl.communityCenter.mapper.PublishCommentMapper;
import com.mcwl.communityCenter.service.PublishCommentLikeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
import java.util.Objects;
/**
*
*
* @AuthorChenYan
* @Projectmcwl-ai
* @Packagecom.mcwl.communityCenter.service.impl
@ -15,5 +30,71 @@ import org.springframework.stereotype.Service;
* @Date2025/1/17 14:25
*/
@Service
public class PublishCommentLikeServiceImpl extends ServiceImpl<PublishCommentLikeMapper, PublishCommentLike>implements PublishCommentLikeService {
@RequiredArgsConstructor
public class PublishCommentLikeServiceImpl extends ServiceImpl<PublishCommentLikeMapper, PublishCommentLike> implements PublishCommentLikeService {
private final PublishCommentMapper publishCommentMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public void like(PublishCommentLikeRes publishCommentLikeRes) {
PublishComment publishComment = publishCommentMapper.selectByIdAndTenantIdAndCommunityIdAndOperatorId(
publishCommentLikeRes.getTenantId(), publishCommentLikeRes.getCommunityId(), publishCommentLikeRes.getCommentId()
);
if (Objects.isNull(publishComment)) {
throw new ServiceException("该评论不存在", HttpStatus.SHOW_ERROR_MSG);
}
PublishCommentLike publishCommentLike = baseMapper.selectLike(publishCommentLikeRes, SecurityUtils.getUserId());
if (Objects.isNull(publishCommentLike)) {
publishCommentLike = new PublishCommentLike();
publishCommentLike.setTenantId(publishCommentLikeRes.getTenantId());
publishCommentLike.setCommunityId(publishCommentLikeRes.getCommunityId());
publishCommentLike.setPublishId(publishCommentLikeRes.getPublishId());
publishCommentLike.setPublishCommentId(publishCommentLikeRes.getCommentId());
publishCommentLike.setUserId(SecurityUtils.getUserId());
baseMapper.insert(publishCommentLike);
publishComment.setLikeNum(publishComment.getLikeNum() + 1);
publishCommentMapper.updateById(publishComment);
this.addLikeAdvice();
return;
}
if (Objects.equals(publishCommentLike.getDelFlag(), "0")) {
publishCommentLike.setDelFlag("2");
int likeNum = publishComment.getLikeNum() - 1;
likeNum = Math.max(likeNum, 0);
publishComment.setLikeNum(likeNum);
} else {
publishCommentLike.setDelFlag("0");
publishComment.setLikeNum(publishComment.getLikeNum() + 1);
this.addLikeAdvice();
}
baseMapper.updateDelFlagById(publishCommentLike);
publishCommentMapper.updateById(publishComment);
}
private void addLikeAdvice(PublishCommentLike publishCommentLike) {
CommunityAdvice communityAdvice = new CommunityAdvice();
communityAdvice.setTenantId(publishCommentLike.getTenantId());
communityAdvice.setCommunityId(publishCommentLike.getCommunityId());
communityAdvice.setSendUserId(SecurityUtils.getUserId());
communityAdvice.setAdviceType(AdviceConstant.COMMUNITY_NOTICE);
communityAdvice.setUserId(publishCommentLike);
communityAdvice.setTitle(StringUtils.format("{}回复{}",
SecurityUtils.getLoginUser().getUser().getNickName(),
question.getContent()));
communityAdvice.setContent(questionCommentRes.getContent());
communityAdviceMapper.insert(communityAdvice);
}
}

View File

@ -0,0 +1,90 @@
package com.mcwl.communityCenter.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.communityCenter.constant.AdviceConstant;
import com.mcwl.communityCenter.domain.*;
import com.mcwl.communityCenter.domain.dto.PublishCommentLikeRes;
import com.mcwl.communityCenter.domain.dto.PublishLikeRes;
import com.mcwl.communityCenter.mapper.*;
import com.mcwl.communityCenter.service.PublishCommentLikeService;
import com.mcwl.communityCenter.service.PublishLikeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Objects;
/**
*
*/
@Service
@RequiredArgsConstructor
public class PublishLikeServiceImpl extends ServiceImpl<PublishLikeMapper, PublishLike> implements PublishLikeService {
private final PublishMapper publishMapper;
private final CommunityAdviceMapper communityAdviceMapper;
@Override
public void like(PublishLikeRes publishLikeRes) {
Publish publish = publishMapper.selectByIdAndTenantIdAndCommunityId(publishLikeRes.getPublishId(),
publishLikeRes.getTenantId(),
publishLikeRes.getCommunityId());
if (Objects.isNull(publish)) {
throw new ServiceException("点赞失败,该内容不存在", HttpStatus.SHOW_ERROR_MSG);
}
PublishLike publishLike = baseMapper.selectPublishLike(publishLikeRes, SecurityUtils.getUserId());
if (Objects.isNull(publishLike)) {
publishLike = PublishLike.builder()
.tenantId(publishLikeRes.getTenantId())
.communityId(publishLikeRes.getCommunityId())
.publishId(publishLikeRes.getPublishId())
.userId(SecurityUtils.getUserId())
.build();
baseMapper.insert(publishLike);
publish.setLikeNum(publish.getLikeNum() + 1);
publishMapper.updateById(publish);
this.addLikeAdvice(publish);
return;
}
if (Objects.equals(publishLike.getDelFlag(), "0")) {
publishLike.setDelFlag("2");
int likeNum = publish.getLikeNum() - 1;
likeNum = Math.max(likeNum, 0);
publish.setLikeNum(likeNum);
} else {
publishLike.setDelFlag("0");
publish.setLikeNum(publish.getLikeNum() + 1);
this.addLikeAdvice(publish);
}
baseMapper.updateDelFlagById(publishLike);
publishMapper.updateById(publish);
}
private void addLikeAdvice(Publish publish) {
CommunityAdvice communityAdvice = new CommunityAdvice();
communityAdvice.setTenantId(publish.getTenantId());
communityAdvice.setCommunityId(publish.getCommunityId());
communityAdvice.setSendUserId(SecurityUtils.getUserId());
communityAdvice.setAdviceType(AdviceConstant.COMMUNITY_NOTICE);
communityAdvice.setUserId(publish.getUserId());
communityAdvice.setContent(StringUtils.format("{}点赞了你发布的{}",
SecurityUtils.getLoginUser().getUser().getNickName(), publish.getContent()));
communityAdviceMapper.insert(communityAdvice);
}
}

View File

@ -11,7 +11,9 @@ import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.communityCenter.constant.AdviceConstant;
import com.mcwl.communityCenter.domain.Community;
import com.mcwl.communityCenter.domain.CommunityAdvice;
import com.mcwl.communityCenter.domain.Question;
import com.mcwl.communityCenter.domain.QuestionComment;
import com.mcwl.communityCenter.domain.dto.*;
@ -38,7 +40,10 @@ public class QuestionCommentServiceImpl extends ServiceImpl<QuestionCommentMappe
private final ISysUserService sysUserService;
private final CommunityAdviceMapper communityAdviceMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public R<Object> comment(QuestionCommentRes questionCommentRes) {
Long tenantId = questionCommentRes.getTenantId();
@ -48,7 +53,7 @@ public class QuestionCommentServiceImpl extends ServiceImpl<QuestionCommentMappe
Question question = questionMapper.selectByIdAndTenantIdAndCommunityId(questionId, tenantId, communityId);
if (Objects.isNull(question)) {
return R.fail(HttpStatus.SHOW_ERROR_MSG,"提问不存在");
return R.fail(HttpStatus.SHOW_ERROR_MSG, "提问不存在");
}
QuestionComment questionComment = new QuestionComment();
@ -57,6 +62,19 @@ public class QuestionCommentServiceImpl extends ServiceImpl<QuestionCommentMappe
baseMapper.insert(questionComment);
CommunityAdvice communityAdvice = new CommunityAdvice();
communityAdvice.setTenantId(tenantId);
communityAdvice.setCommunityId(communityId);
communityAdvice.setSendUserId(SecurityUtils.getUserId());
communityAdvice.setAdviceType(AdviceConstant.COMMUNITY_NOTICE);
communityAdvice.setUserId(question.getQuestionUserId());
communityAdvice.setTitle(StringUtils.format("{}回复{}",
SecurityUtils.getLoginUser().getUser().getNickName(),
question.getContent()));
communityAdvice.setContent(questionCommentRes.getContent());
communityAdviceMapper.insert(communityAdvice);
return R.ok(null, "评论成功");
}
@ -98,25 +116,25 @@ public class QuestionCommentServiceImpl extends ServiceImpl<QuestionCommentMappe
Question question = questionMapper.selectByIdAndTenantIdAndCommunityId(questionId, tenantId, communityId);
if (Objects.isNull(question)) {
return R.fail(HttpStatus.SHOW_ERROR_MSG,"提问不存在");
return R.fail(HttpStatus.SHOW_ERROR_MSG, "提问不存在");
}
if (question.getStatus() == 1) {
return R.fail(HttpStatus.SHOW_ERROR_MSG,"该提问已解决");
return R.fail(HttpStatus.SHOW_ERROR_MSG, "该提问已解决");
}
QuestionComment questionComment = baseMapper.selectByIdAndTenantIdAndCommunityIdAndQuestionIdAndCommentId(tenantId, communityId, questionId, commentId);
if (Objects.isNull(questionComment)) {
return R.fail(HttpStatus.SHOW_ERROR_MSG,"评论不存在");
return R.fail(HttpStatus.SHOW_ERROR_MSG, "评论不存在");
}
if (questionComment.getIsAccept() == 1) {
return R.fail(HttpStatus.SHOW_ERROR_MSG,"该评论已被采纳");
return R.fail(HttpStatus.SHOW_ERROR_MSG, "该评论已被采纳");
}
Long questionUserId = question.getQuestionUserId();
if (questionComment.getUserId().equals(questionUserId)) {
return R.fail(HttpStatus.SHOW_ERROR_MSG,"您不能采纳自己的评论");
return R.fail(HttpStatus.SHOW_ERROR_MSG, "您不能采纳自己的评论");
}
questionComment.setIsAccept(1);

View File

@ -12,6 +12,7 @@ import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.communityCenter.constant.AdviceConstant;
import com.mcwl.communityCenter.constant.StatusConstant;
import com.mcwl.communityCenter.domain.Community;
import com.mcwl.communityCenter.domain.CommunityAdvice;
@ -65,21 +66,22 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
// 获取租户id
Long tenantId = questionRes.getTenantId();
Long questionUserId = questionRes.getQuestionUserId();
Community community = communityMapper.getByTenantIdAndCommunityId(tenantId, communityId);
if (Objects.isNull(community)) {
return R.fail(HttpStatus.SHOW_ERROR_MSG,"租户或社区不存在");
return R.fail(HttpStatus.SHOW_ERROR_MSG, "租户或社区不存在");
}
if (Objects.equals(tenantId, userId)) {
return R.fail(HttpStatus.SHOW_ERROR_MSG,"您不能提问自己的问题");
if (Objects.equals(questionUserId, userId)) {
return R.fail(HttpStatus.SHOW_ERROR_MSG, "您不能提问自己的问题");
}
//提问人userId是否在社区中
Invite invite = inviteMapper.selectByTenantIdAndCommunityIdAndInviteeUserId(tenantId, communityId, userId);
if (Objects.isNull(invite)) {
return R.fail(HttpStatus.SHOW_ERROR_MSG,"您不是该社区成员,不能提问");
return R.fail(HttpStatus.SHOW_ERROR_MSG, "您不是该社区成员,不能提问");
}
Question question = new Question();
@ -100,13 +102,15 @@ public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> i
sysUserService.updateUser(sysUser);
// CommunityAdvice communityAdvice = new CommunityAdvice();
// communityAdvice.setTenantId(tenantId);
// communityAdvice.setCommunityId(communityId);
// communityAdvice.setUserId(tenantId);
// communityAdvice.setTitle("您有新的问题");
// communityAdvice.setContent(questionRes.getContent());
// communityAdviceMapper.insert(communityAdvice);
CommunityAdvice communityAdvice = new CommunityAdvice();
communityAdvice.setTenantId(tenantId);
communityAdvice.setCommunityId(communityId);
communityAdvice.setSendUserId(SecurityUtils.getUserId());
communityAdvice.setAdviceType(AdviceConstant.WAIT_ME_ANSWER);
communityAdvice.setUserId(questionUserId);
communityAdvice.setTitle(StringUtils.format("{}向你提问:", SecurityUtils.getLoginUser().getUser().getNickName()));
communityAdvice.setContent(questionRes.getContent());
communityAdviceMapper.insert(communityAdvice);
return R.ok();

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mcwl.communityCenter.mapper.PublishCommentLikeMapper">
<update id="updateDelFlagById">
update cc_comment_like
set del_flag = #{publishCommentLike.delFlag}
where tenant_id = #{publishCommentLike.tenantId}
and community_id = #{publishCommentLike.communityId}
and comment_id = #{publishCommentLike.publishCommentId}
</update>
<select id="selectByTenantIdAndCommunityIdAndCommentId"
resultType="com.mcwl.communityCenter.domain.PublishCommentLike">
select * from cc_comment_like
where tenant_id = #{tenantId}
and community_id = #{communityId}
and comment_id = #{commentId}
</select>
<select id="selectLike" resultType="com.mcwl.communityCenter.domain.PublishCommentLike">
select * from cc_comment_like
where tenant_id = #{publishCommentLikeRes.tenantId}
and community_id = #{publishCommentLikeRes.communityId}
and publish_id = #{publishCommentLikeRes.publishId}
and comment_id = #{publishCommentLikeRes.commentId}
and user_id = #{userId}
</select>
</mapper>

View File

@ -5,8 +5,7 @@
<mapper namespace="com.mcwl.communityCenter.mapper.PublishCommentMapper">
<update id="deleteByIdAndTenantIdAndCommunityIdAndOperatorId">
update cc_comment set del_flag = '2'
where id = #{id}
and tenant_id = #{tenantId}
where tenant_id = #{tenantId}
and community_id = #{communityId}
and operator_id = #{operatorId}
and type = 0
@ -45,8 +44,7 @@
like_num,
create_time
from cc_comment
where id = #{id}
and tenant_id = #{tenantId}
where tenant_id = #{tenantId}
and community_id = #{communityId}
and operator_id = #{operatorId}
and type = 0

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mcwl.communityCenter.mapper.PublishLikeMapper">
<update id="updateDelFlagById">
update cc_publish_like
set del_flag = #{publishLike.delFlag}
where tenant_id = #{publishLike.tenantId}
and community_id = #{publishLike.communityId}
and publish_id = #{publishLike.publishId}
and user_id = #{publishLike.userId}
</update>
<select id="selectPublishLike" resultType="com.mcwl.communityCenter.domain.PublishLike">
select *
from cc_publish_like
where tenant_id = #{publishLikeRes.tenantId}
and community_id = #{publishLikeRes.communityId}
and publish_id = #{publishLikeRes.publishId}
and user_id = #{userId}
</select>
</mapper>

View File

@ -20,7 +20,7 @@ public class Benefit extends BaseEntity {
/**
* Id
*/
private String benefitNameId;
private Long benefitNameId;
/**
*
*/

View File

@ -18,12 +18,12 @@ public class AddBenefitNameDto {
*
*/
@ApiModelProperty(value = "权益名称", required = true)
@NotNull(message = "权益名称不能为空")
@NotBlank(message = "权益名称不能为空")
private String benefitName;
/**
*
*/
@NotBlank(message = "排序不能为空")
@NotNull(message = "排序不能为空")
@ApiModelProperty(value = "排序", required = true)
private Integer benefitOrder;

View File

@ -6,6 +6,7 @@ import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
/**
*
@ -20,12 +21,12 @@ public class EditBenefitNameDto {
*
*/
@ApiModelProperty(value = "权益名称", required = true)
@NotNull(message = "权益名称不能为空")
@NotBlank(message = "权益名称不能为空")
private String benefitName;
/**
*
*/
@NotBlank(message = "排序不能为空")
@NotNull(message = "排序不能为空")
@ApiModelProperty(value = "排序", required = true)
private Integer benefitOrder;

View File

@ -39,10 +39,10 @@
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.2</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.eclipse.paho</groupId>-->
<!-- <artifactId>org.eclipse.paho.client.mqttv3</artifactId>-->
<!-- <version>1.2.2</version>-->
<!-- </dependency>-->
</dependencies>
</project>

View File

@ -1,38 +0,0 @@
package com.mcwl.resource.handler;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.lang.annotation.*;
import java.util.Collections;
import java.util.List;
public interface IMessageHandler {
void handleMessage(String topic, MqttMessage message);
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Topic {
String value();
int qos() default 1;
}
default List<TopicSubscription> getTopics() {
Topic annotation = this.getClass().getAnnotation(Topic.class);
if (annotation != null) {
return Collections.singletonList(
new TopicSubscription(annotation.value(), annotation.qos())
);
}
return Collections.emptyList();
}
@Getter
@AllArgsConstructor
class TopicSubscription {
private String topicFilter;
private int qos;
}
}

View File

@ -1,127 +0,0 @@
package com.mcwl.resource.handler.impl;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.domain.ModelImageComment;
import com.mcwl.resource.domain.ModelImageCommentLike;
import com.mcwl.resource.domain.SysAdvice;
import com.mcwl.resource.handler.IMessageHandler;
import com.mcwl.resource.mapper.ModelImageCommentLikeMapper;
import com.mcwl.resource.mapper.ModelImageCommentMapper;
import com.mcwl.resource.mapper.WorkFlowCommentLikeMapper;
import com.mcwl.resource.mapper.WorkFlowCommentMapper;
import com.mcwl.resource.service.ISysAdviceService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
import java.util.Objects;
@Slf4j
@Component
@IMessageHandler.Topic(value = "imageCommentLike/#", qos = 1)
@RequiredArgsConstructor
public class ImageCommentLikeHandler implements IMessageHandler {
private final ModelImageCommentMapper modelImageCommentMapper;
private final ModelImageCommentLikeMapper modelImageCommentLikeMapper;
private final ISysUserService userService;
private final ISysAdviceService adviceService;
@Override
@Transactional(rollbackFor = Exception.class)
public void handleMessage(String topic, MqttMessage message) {
String payload = new String(message.getPayload());
log.info("图片评论点赞: {} - {}", payload, message);
JSON parse = JSONUtil.parse(payload);
Long commentId = Long.parseLong(parse.getByPath("commentId").toString());
Long userId = Long.parseLong(parse.getByPath("userId").toString());
this.like(userId, commentId);
}
private void like(Long userId, Long commentId) {
ModelImageComment modelImageComment = modelImageCommentMapper.selectById(commentId);
if (Objects.isNull(modelImageComment)) {
throw new ServiceException("该评论不存在", HttpStatus.SHOW_ERROR_MSG);
}
ModelImageCommentLike modelImageCommentLike = modelImageCommentLikeMapper.getLikeImageComment(userId, commentId);
if (Objects.nonNull(modelImageCommentLike)) {
if (Objects.equals(modelImageCommentLike.getDelFlag(), "0")) {
modelImageCommentLike.setDelFlag("2");
int likeNum = modelImageComment.getLikeNum() - 1;
likeNum = Math.max(likeNum, 0);
modelImageComment.setLikeNum(likeNum);
} else {
modelImageCommentLike.setDelFlag("0");
modelImageComment.setLikeNum(modelImageComment.getLikeNum() + 1);
this.addLikeAdvice(modelImageComment, userId);
}
// 更新点赞记录
modelImageCommentLikeMapper.updateDelFlagById(modelImageCommentLike);
// 更新图片评论点赞数
modelImageCommentMapper.updateById(modelImageComment);
return;
}
// 添加点赞记录
modelImageCommentLike = new ModelImageCommentLike();
modelImageCommentLike.setUserId(userId);
modelImageCommentLike.setModelImageCommentId(commentId);
modelImageCommentLikeMapper.insert(modelImageCommentLike);
// 更新图片点赞数
modelImageComment.setLikeNum(modelImageComment.getLikeNum() + 1);
modelImageCommentMapper.updateById(modelImageComment);
this.addLikeAdvice(modelImageComment, userId);
}
private void addLikeAdvice(ModelImageComment modelImageComment, Long userId) {
Long receiverUserId = modelImageComment.getUserId();
if (Objects.equals(userId, receiverUserId)) {
return;
}
SysUser sysUser = userService.selectUserById(userId);
String content = StringUtils.format("恭喜!{}点赞了您的评论",
sysUser.getNickName());
SysAdvice sysAdvice = new SysAdvice();
sysAdvice.setSenderId(userId);
sysAdvice.setReceiverId(receiverUserId);
sysAdvice.setContent(content);
sysAdvice.setProductId(modelImageComment.getModelImageId());
sysAdvice.setProductType(2);
sysAdvice.setCommentId(modelImageComment.getId());
sysAdvice.setIsRead(0);
sysAdvice.setType(AdviceEnum.LIKE_REMIND);
adviceService.save(sysAdvice);
}
}

View File

@ -1,123 +0,0 @@
package com.mcwl.resource.handler.impl;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.domain.ModelImage;
import com.mcwl.resource.domain.ModelImageLike;
import com.mcwl.resource.domain.SysAdvice;
import com.mcwl.resource.handler.IMessageHandler;
import com.mcwl.resource.mapper.ModelImageLikeMapper;
import com.mcwl.resource.mapper.ModelImageMapper;
import com.mcwl.resource.mapper.WorkFlowLikeMapper;
import com.mcwl.resource.mapper.WorkFlowMapper;
import com.mcwl.resource.service.ISysAdviceService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Objects;
@Slf4j
@Component
@IMessageHandler.Topic(value = "imageLike/#", qos = 1)
@RequiredArgsConstructor
public class ImageLikeHandler implements IMessageHandler {
private final ModelImageMapper modelImageMapper;
private final ModelImageLikeMapper modelImageLikeMapper;
private final ISysUserService userService;
private final ISysAdviceService adviceService;
@Override
@Transactional(rollbackFor = Exception.class)
public void handleMessage(String topic, MqttMessage message) {
String payload = new String(message.getPayload());
log.info("图片点赞: {}", payload);
JSON parse = JSONUtil.parse(payload);
Long commentId = Long.parseLong(parse.getByPath("commentId").toString());
Long userId = Long.parseLong(parse.getByPath("userId").toString());
this.like(userId, commentId);
}
private void like(Long userId, Long imageId) {
ModelImage modelImage = modelImageMapper.selectById(imageId);
if (Objects.isNull(modelImage)) {
throw new ServiceException("该图片不存在或已下架", HttpStatus.SHOW_ERROR_MSG);
}
ModelImageLike modelImageLike = modelImageLikeMapper.getLikeImage(userId, imageId);
if (Objects.nonNull(modelImageLike)) {
if (Objects.equals(modelImageLike.getDelFlag(), "0")) {
modelImageLike.setDelFlag("2");
int likeNum = modelImage.getLikeNum() - 1;
likeNum = Math.max(likeNum, 0);
modelImage.setLikeNum(likeNum);
} else {
modelImageLike.setDelFlag("0");
modelImage.setLikeNum(modelImage.getLikeNum() + 1);
this.addLikeAdvice(modelImage, userId);
}
// 更新点赞记录
modelImageLikeMapper.updateDelFlagById(modelImageLike);
// 更新图片点赞数
modelImageMapper.updateById(modelImage);
return;
}
// 添加点赞记录
modelImageLike = new ModelImageLike();
modelImageLike.setUserId(userId);
modelImageLike.setModelImageId(imageId);
modelImageLikeMapper.insert(modelImageLike);
// 更新图片点赞数
modelImage.setLikeNum(modelImage.getLikeNum() + 1);
modelImageMapper.updateById(modelImage);
this.addLikeAdvice(modelImage, userId);
}
private void addLikeAdvice(ModelImage modelImage, Long userId) {
Long receiverUserId = modelImage.getUserId();
if (Objects.equals(userId, receiverUserId)) {
return;
}
SysUser sysUser = userService.selectUserById(userId);
String content = StringUtils.format("恭喜!{}点赞了您的图片:{}",
sysUser.getNickName(), modelImage.getTitle());
SysAdvice sysAdvice = new SysAdvice();
sysAdvice.setSenderId(userId);
sysAdvice.setReceiverId(receiverUserId);
sysAdvice.setContent(content);
sysAdvice.setProductId(modelImage.getId());
sysAdvice.setProductType(2);
sysAdvice.setIsRead(0);
sysAdvice.setType(AdviceEnum.LIKE_REMIND);
adviceService.save(sysAdvice);
}
}

View File

@ -1,122 +0,0 @@
package com.mcwl.resource.handler.impl;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.domain.*;
import com.mcwl.resource.handler.IMessageHandler;
import com.mcwl.resource.mapper.ModelCommentLikeMapper;
import com.mcwl.resource.mapper.ModelCommentMapper;
import com.mcwl.resource.mapper.WorkFlowCommentLikeMapper;
import com.mcwl.resource.mapper.WorkFlowCommentMapper;
import com.mcwl.resource.service.ISysAdviceService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Objects;
@Slf4j
@Component
@IMessageHandler.Topic(value = "modelCommentLike/#", qos = 1)
@RequiredArgsConstructor
public class ModelCommentLikeHandler implements IMessageHandler {
private final ModelCommentMapper modelCommentMapper;
private final ModelCommentLikeMapper modelCommentLikeMapper;
private final ISysUserService userService;
private final ISysAdviceService adviceService;
@Override
@Transactional(rollbackFor = Exception.class)
public void handleMessage(String topic, MqttMessage message) {
String payload = new String(message.getPayload());
log.info("模型评论点赞: {} - {}", payload, message);
JSON parse = JSONUtil.parse(payload);
Long commentId = Long.parseLong(parse.getByPath("commentId").toString());
Long userId = Long.parseLong(parse.getByPath("userId").toString());
this.like(userId, commentId);
}
private void like(Long userId, Long commentId) {
ModelComment modelComment = modelCommentMapper.selectById(commentId);
if (Objects.isNull(modelComment)) {
throw new ServiceException("该评论不存在", HttpStatus.SHOW_ERROR_MSG);
}
ModelCommentLike modelCommentLike = modelCommentLikeMapper.getLikeComment(userId, commentId);
if (Objects.nonNull(modelCommentLike)) {
if (Objects.equals(modelCommentLike.getDelFlag(), "0")) {
modelCommentLike.setDelFlag("2");
int likeNum = modelComment.getLikeNum() - 1;
likeNum = Math.max(likeNum, 0);
modelComment.setLikeNum(likeNum);
} else {
modelCommentLike.setDelFlag("0");
modelComment.setLikeNum(modelComment.getLikeNum() + 1);
this.addLikeAdvice(modelComment, userId);
}
// 更新点赞记录
modelCommentLikeMapper.updateDelFlagById(modelCommentLike);
// 更新图片评论点赞数
modelCommentMapper.updateById(modelComment);
return;
}
// 添加点赞记录
modelCommentLike = new ModelCommentLike();
modelCommentLike.setUserId(userId);
modelCommentLike.setModelCommentId(commentId);
modelCommentLikeMapper.insert(modelCommentLike);
// 更新模型点赞数
modelComment.setLikeNum(modelComment.getLikeNum() + 1);
modelCommentMapper.updateById(modelComment);
this.addLikeAdvice(modelComment, userId);
}
private void addLikeAdvice(ModelComment modelComment, Long userId) {
Long receiverUserId = modelComment.getUserId();
if (Objects.equals(userId, receiverUserId)) {
return;
}
SysUser sysUser = userService.selectUserById(userId);
String content = StringUtils.format("恭喜!{}点赞了您的评论",
sysUser.getNickName());
SysAdvice sysAdvice = new SysAdvice();
sysAdvice.setSenderId(userId);
sysAdvice.setReceiverId(receiverUserId);
sysAdvice.setContent(content);
sysAdvice.setProductId(modelComment.getModelId());
sysAdvice.setProductType(0);
sysAdvice.setCommentId(modelComment.getId());
sysAdvice.setIsRead(0);
sysAdvice.setType(AdviceEnum.LIKE_REMIND);
adviceService.save(sysAdvice);
}
}

View File

@ -1,121 +0,0 @@
package com.mcwl.resource.handler.impl;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.domain.*;
import com.mcwl.resource.handler.IMessageHandler;
import com.mcwl.resource.mapper.ModelLikeMapper;
import com.mcwl.resource.mapper.ModelMapper;
import com.mcwl.resource.mapper.WorkFlowLikeMapper;
import com.mcwl.resource.mapper.WorkFlowMapper;
import com.mcwl.resource.service.ISysAdviceService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Objects;
@Slf4j
@Component
@IMessageHandler.Topic(value = "modelLike/#", qos = 1)
@RequiredArgsConstructor
public class ModelLikeHandler implements IMessageHandler {
private final ModelMapper modelMapper;
private final ModelLikeMapper modelLikeMapper;
private final ISysUserService userService;
private final ISysAdviceService adviceService;
@Override
@Transactional(rollbackFor = Exception.class)
public void handleMessage(String topic, MqttMessage message) {
String payload = new String(message.getPayload());
log.info("模型点赞: {}", payload);
JSON parse = JSONUtil.parse(payload);
Long commentId = Long.parseLong(parse.getByPath("commentId").toString());
Long userId = Long.parseLong(parse.getByPath("userId").toString());
this.like(userId, commentId);
}
private void like(Long userId, Long modelId) {
ModelProduct model = modelMapper.selectById(modelId);
if (Objects.isNull(model)) {
throw new ServiceException("该模型不存在或已下架", HttpStatus.SHOW_ERROR_MSG);
}
ModelLike modelLike = modelLikeMapper.getLike(userId, modelId);
if (Objects.nonNull(modelLike)) {
if (Objects.equals(modelLike.getDelFlag(), "0")) {
modelLike.setDelFlag("2");
int likeNum = model.getLikeNum() - 1;
likeNum = Math.max(likeNum, 0);
model.setLikeNum(likeNum);
} else {
modelLike.setDelFlag("0");
model.setLikeNum(model.getLikeNum() + 1);
this.addLikeAdvice(model, userId);
}
// 更新点赞记录
modelLikeMapper.updateDelFlagById(modelLike);
// 更新图片点赞数
modelMapper.updateById(model);
return;
}
// 添加点赞记录
modelLike = new ModelLike();
modelLike.setUserId(userId);
modelLike.setModelId(modelId);
modelLikeMapper.insert(modelLike);
// 更新图片点赞数
model.setNumbers(model.getLikeNum() + 1);
modelMapper.updateById(model);
this.addLikeAdvice(model, userId);
}
private void addLikeAdvice(ModelProduct model, Long userId) {
Long receiverUserId = model.getUserId();
if (Objects.equals(userId, receiverUserId)) {
return;
}
SysUser sysUser = userService.selectUserById(userId);
String content = StringUtils.format("恭喜!{}点赞了您的模型:{}",
sysUser.getNickName(), model.getModelName());
SysAdvice sysAdvice = new SysAdvice();
sysAdvice.setSenderId(userId);
sysAdvice.setReceiverId(receiverUserId);
sysAdvice.setContent(content);
sysAdvice.setProductId(model.getId());
sysAdvice.setProductType(0);
sysAdvice.setIsRead(0);
sysAdvice.setType(AdviceEnum.LIKE_REMIND);
adviceService.save(sysAdvice);
}
}

View File

@ -1,125 +0,0 @@
package com.mcwl.resource.handler.impl;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.domain.SysAdvice;
import com.mcwl.resource.domain.WorkFlowComment;
import com.mcwl.resource.domain.WorkFlowCommentLike;
import com.mcwl.resource.handler.IMessageHandler;
import com.mcwl.resource.mapper.WorkFlowCommentLikeMapper;
import com.mcwl.resource.mapper.WorkFlowCommentMapper;
import com.mcwl.resource.service.ISysAdviceService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Objects;
@Slf4j
@Component
@IMessageHandler.Topic(value = "workFlowCommentLike/#", qos = 1)
@RequiredArgsConstructor
public class WorkFlowCommentLikeHandler implements IMessageHandler {
private final WorkFlowCommentMapper workFlowCommentMapper;
private final WorkFlowCommentLikeMapper workFlowCommentLikeMapper;
private final ISysUserService userService;
private final ISysAdviceService adviceService;
@Override
@Transactional(rollbackFor = Exception.class)
public void handleMessage(String topic, MqttMessage message) {
String payload = new String(message.getPayload());
log.info("工作流评论点赞: {} - {}", topic, payload);
JSON parse = JSONUtil.parse(payload);
Long commentId = Long.parseLong(parse.getByPath("commentId").toString());
Long userId = Long.parseLong(parse.getByPath("userId").toString());
this.like(userId, commentId);
}
private void like(Long userId, Long commentId) {
WorkFlowComment workFlowComment = workFlowCommentMapper.selectById(commentId);
if (Objects.isNull(workFlowComment)) {
throw new ServiceException("该评论不存在", HttpStatus.SHOW_ERROR_MSG);
}
WorkFlowCommentLike workFlowCommentLike = workFlowCommentLikeMapper.getLikeComment(userId, commentId);
if (Objects.nonNull(workFlowCommentLike)) {
if (Objects.equals(workFlowCommentLike.getDelFlag(), "0")) {
workFlowCommentLike.setDelFlag("2");
int likeNum = workFlowComment.getLikeNum() - 1;
likeNum = Math.max(likeNum, 0);
workFlowComment.setLikeNum(likeNum);
} else {
workFlowCommentLike.setDelFlag("0");
workFlowComment.setLikeNum(workFlowComment.getLikeNum() + 1);
this.addLikeAdvice(workFlowComment, userId);
}
// 更新点赞记录
workFlowCommentLikeMapper.updateDelFlagById(workFlowCommentLike);
// 更新图片评论点赞数
workFlowCommentMapper.updateById(workFlowComment);
return;
}
// 添加点赞记录
workFlowCommentLike = new WorkFlowCommentLike();
workFlowCommentLike.setUserId(userId);
workFlowCommentLike.setWorkFlowCommentId(commentId);
workFlowCommentLikeMapper.insert(workFlowCommentLike);
// 更新模型点赞数
workFlowComment.setLikeNum(workFlowComment.getLikeNum() + 1);
workFlowCommentMapper.updateById(workFlowComment);
this.addLikeAdvice(workFlowComment, userId);
}
private void addLikeAdvice(WorkFlowComment workFlowComment, Long userId) {
Long receiverUserId = workFlowComment.getUserId();
if (Objects.equals(userId, receiverUserId)) {
return;
}
SysUser sysUser = userService.selectUserById(userId);
String content = StringUtils.format("恭喜!{}点赞了您的评论",
sysUser.getNickName());
SysAdvice sysAdvice = new SysAdvice();
sysAdvice.setSenderId(userId);
sysAdvice.setReceiverId(receiverUserId);
sysAdvice.setContent(content);
sysAdvice.setProductId(workFlowComment.getWorkFlowId());
sysAdvice.setProductType(1);
sysAdvice.setCommentId(workFlowComment.getId());
sysAdvice.setIsRead(0);
sysAdvice.setType(AdviceEnum.LIKE_REMIND);
adviceService.save(sysAdvice);
}
}

View File

@ -1,119 +0,0 @@
package com.mcwl.resource.handler.impl;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.exception.ServiceException;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.domain.SysAdvice;
import com.mcwl.resource.domain.WorkFlow;
import com.mcwl.resource.domain.WorkFlowLike;
import com.mcwl.resource.handler.IMessageHandler;
import com.mcwl.resource.mapper.WorkFlowLikeMapper;
import com.mcwl.resource.mapper.WorkFlowMapper;
import com.mcwl.resource.service.ISysAdviceService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Objects;
@Slf4j
@Component
@IMessageHandler.Topic(value = "workFlowLike/#", qos = 1)
@RequiredArgsConstructor
public class WorkFlowLikeHandler implements IMessageHandler {
private final WorkFlowMapper workFlowMapper;
private final WorkFlowLikeMapper workFlowLikeMapper;
private final ISysUserService userService;
private final ISysAdviceService adviceService;
@Override
@Transactional(rollbackFor = Exception.class)
public void handleMessage(String topic, MqttMessage message) {
String payload = new String(message.getPayload());
log.info("工作流点赞: {} - {}", topic, payload);
JSON parse = JSONUtil.parse(payload);
Long commentId = Long.parseLong(parse.getByPath("commentId").toString());
Long userId = Long.parseLong(parse.getByPath("userId").toString());
this.like(userId, commentId);
}
private void like(Long userId, Long modelId) {
WorkFlow workFlow = workFlowMapper.selectById(modelId);
if (Objects.isNull(workFlow)) {
throw new ServiceException("该工作流不存在或已下架", HttpStatus.SHOW_ERROR_MSG);
}
WorkFlowLike workFlowLike = workFlowLikeMapper.getLike(userId, modelId);
if (Objects.nonNull(workFlowLike)) {
if (Objects.equals(workFlowLike.getDelFlag(), "0")) {
workFlowLike.setDelFlag("2");
int likeCount = workFlow.getLikeNum() - 1;
likeCount = Math.max(likeCount, 0);
workFlow.setLikeNum(likeCount);
} else {
workFlowLike.setDelFlag("0");
workFlow.setLikeNum(workFlow.getLikeNum() + 1);
this.addLikeAdvice(workFlow, userId);
}
// 更新点赞记录
workFlowLikeMapper.updateStatus(workFlowLike);
// 更新图片点赞数
workFlowMapper.updateById(workFlow);
return;
}
// 添加点赞记录
workFlowLike = new WorkFlowLike();
workFlowLike.setUserId(userId);
workFlowLike.setWorkFlowId(modelId);
workFlowLikeMapper.insert(workFlowLike);
// 更新图片点赞数
workFlow.setLikeNum(workFlow.getLikeNum() + 1);
workFlowMapper.updateById(workFlow);
this.addLikeAdvice(workFlow, userId);
}
private void addLikeAdvice(WorkFlow workFlow, Long userId) {
Long receiverUserId = workFlow.getUserId();
if (Objects.equals(userId, receiverUserId)) {
return;
}
SysUser sysUser = userService.selectUserById(userId);
String content = StringUtils.format("恭喜!{}点赞了您的工作流:{}",
sysUser.getNickName(), workFlow.getWorkflowName());
SysAdvice sysAdvice = new SysAdvice();
sysAdvice.setSenderId(userId);
sysAdvice.setReceiverId(receiverUserId);
sysAdvice.setContent(content);
sysAdvice.setProductId(workFlow.getId());
sysAdvice.setProductType(1);
sysAdvice.setIsRead(0);
sysAdvice.setType(AdviceEnum.LIKE_REMIND);
adviceService.save(sysAdvice);
}
}

View File

@ -7,7 +7,6 @@ import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.resource.domain.ModelCommentLike;
import com.mcwl.resource.mapper.ModelCommentLikeMapper;
import com.mcwl.resource.service.ModelCommentLikeService;
import com.mcwl.resource.util.MqttTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -22,8 +21,6 @@ import java.util.Map;
@Service
public class ModelCommentLikeServiceImpl extends ServiceImpl<ModelCommentLikeMapper, ModelCommentLike> implements ModelCommentLikeService {
@Autowired
private MqttTemplate mqttTemplate;
@Autowired
private RabbitTemplate rabbitTemplate;
@ -33,7 +30,6 @@ public class ModelCommentLikeServiceImpl extends ServiceImpl<ModelCommentLikeMap
Map<String, Long> map = new HashMap<>();
map.put("userId", SecurityUtils.getUserId());
map.put("commentId", commentId);
// mqttTemplate.publish("modelCommentLike", JSONUtil.toJsonStr(map), 0);
rabbitTemplate.convertAndSend(QueueConstants.MODEL_COMMENT_LIKE_QUEUE, map);
}

View File

@ -7,7 +7,6 @@ import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.resource.domain.ModelImageCommentLike;
import com.mcwl.resource.mapper.ModelImageCommentLikeMapper;
import com.mcwl.resource.service.ModelImageCommentLikeService;
import com.mcwl.resource.util.MqttTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
@ -24,7 +23,6 @@ import java.util.Map;
@RequiredArgsConstructor
public class ModelImageCommentLikeServiceImpl extends ServiceImpl<ModelImageCommentLikeMapper, ModelImageCommentLike> implements ModelImageCommentLikeService {
private final MqttTemplate mqttTemplate;
private final RabbitTemplate rabbitTemplate;
@ -34,7 +32,6 @@ public class ModelImageCommentLikeServiceImpl extends ServiceImpl<ModelImageComm
Map<String, Long> map = new HashMap<>();
map.put("userId", SecurityUtils.getUserId());
map.put("commentId", commentId);
// mqttTemplate.publish("imageCommentLike", JSONUtil.toJsonStr(map),0);
rabbitTemplate.convertAndSend(QueueConstants.IMAGE_COMMENT_LIKE_QUEUE, map);
}

View File

@ -25,7 +25,6 @@ import com.mcwl.resource.domain.vo.PageVo;
import com.mcwl.resource.mapper.ModelImageLikeMapper;
import com.mcwl.resource.mapper.ModelImageMapper;
import com.mcwl.resource.service.ModelImageLikeService;
import com.mcwl.resource.util.MqttTemplate;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
@ -47,9 +46,6 @@ public class ModelImageLikeServiceImpl extends ServiceImpl<ModelImageLikeMapper,
private final ISysUserService sysUserService;
@Autowired
private MqttTemplate mqttTemplate;
private final RabbitTemplate rabbitTemplate;
@Override
@ -57,7 +53,6 @@ public class ModelImageLikeServiceImpl extends ServiceImpl<ModelImageLikeMapper,
Map<String, Long> map = new HashMap<>();
map.put("userId", SecurityUtils.getUserId());
map.put("commentId", imageId);
// mqttTemplate.publish("imageLike", JSONUtil.toJsonStr(map),0);
Long userId = SecurityUtils.getUserId();
rabbitTemplate.convertAndSend(QueueConstants.IMAGE_LIKE_QUEUE, map);
}

View File

@ -20,7 +20,6 @@ import com.mcwl.resource.domain.vo.ModelLikeVo;
import com.mcwl.resource.mapper.ModelLikeMapper;
import com.mcwl.resource.mapper.ModelMapper;
import com.mcwl.resource.service.ModelLikeService;
import com.mcwl.resource.util.MqttTemplate;
import com.mcwl.system.service.ISysUserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
@ -41,9 +40,6 @@ public class ModelLikeServiceImpl extends ServiceImpl<ModelLikeMapper, ModelLike
@Autowired
private ISysUserService sysUserService;
@Autowired
private MqttTemplate mqttTemplate;
@Autowired
private RabbitTemplate rabbitTemplate;
@ -53,7 +49,6 @@ public class ModelLikeServiceImpl extends ServiceImpl<ModelLikeMapper, ModelLike
Map<String, Long> map = new HashMap<>();
map.put("userId", SecurityUtils.getUserId());
map.put("commentId", modelId);
// mqttTemplate.publish("modelLike", JSONUtil.toJsonStr(map), 0);
rabbitTemplate.convertAndSend(QueueConstants.MODEL_LIKE_QUEUE, map);
}

View File

@ -7,7 +7,6 @@ import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.resource.domain.WorkFlowCommentLike;
import com.mcwl.resource.mapper.WorkFlowCommentLikeMapper;
import com.mcwl.resource.service.WorkFlowCommentLikeService;
import com.mcwl.resource.util.MqttTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -27,9 +26,6 @@ import java.util.Map;
@Service
public class WorkFlowCommentLikeServiceImpl extends ServiceImpl<WorkFlowCommentLikeMapper, WorkFlowCommentLike> implements WorkFlowCommentLikeService {
@Autowired
private MqttTemplate mqttTemplate;
@Autowired
private RabbitTemplate rabbitTemplate;
@ -38,7 +34,6 @@ public class WorkFlowCommentLikeServiceImpl extends ServiceImpl<WorkFlowCommentL
Map<String, Long> map = new HashMap<>();
map.put("userId", SecurityUtils.getUserId());
map.put("commentId", commentId);
// mqttTemplate.publish("workFlowCommentLike", JSONUtil.toJsonStr(map),0);
rabbitTemplate.convertAndSend(QueueConstants.WORK_FLOW_COMMENT_LIKE_QUEUE, map);
}

View File

@ -20,7 +20,6 @@ import com.mcwl.resource.domain.vo.WorkFlowLikeVo;
import com.mcwl.resource.mapper.WorkFlowLikeMapper;
import com.mcwl.resource.mapper.WorkFlowMapper;
import com.mcwl.resource.service.WorkFlowLikeService;
import com.mcwl.resource.util.MqttTemplate;
import com.mcwl.system.service.ISysUserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
@ -48,9 +47,6 @@ public class WorkFlowLikeServiceImpl extends ServiceImpl<WorkFlowLikeMapper, Wor
@Autowired
private ISysUserService sysUserService;
@Autowired
private MqttTemplate mqttTemplate;
@Autowired
private RabbitTemplate rabbitTemplate;
@ -59,7 +55,6 @@ public class WorkFlowLikeServiceImpl extends ServiceImpl<WorkFlowLikeMapper, Wor
Map<String, Long> map = new HashMap<>();
map.put("userId", SecurityUtils.getUserId());
map.put("commentId", modelId);
// mqttTemplate.publish("workFlowLike", JSONUtil.toJsonStr(map),0);
rabbitTemplate.convertAndSend(QueueConstants.WORK_FLOW_LIKE_QUEUE, map);
}

View File

@ -1,264 +0,0 @@
package com.mcwl.resource.util;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.handler.IMessageHandler;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static com.mcwl.common.utils.Threads.sleep;
@Slf4j
@Getter
@Configuration
@ConfigurationProperties(prefix = "mqtt")
public class MqttTemplate implements MqttCallbackExtended, DisposableBean {
@Value("${mqtt.broker-url}")
private String brokerUrl;
@Value("${mqtt.client-id-prefix}")
private String clientIdPrefix;
@Value("${mqtt.connection-timeout}")
private int connectionTimeout;
@Value("${mqtt.keep-alive-interval}")
private int keepAliveInterval;
@Value("${mqtt.max-reconnect-attempts}")
private int maxReconnectAttempts;
@Value("${mqtt.clean-session}")
private boolean cleanSession;
private String clientId;
private MqttAsyncClient client;
private final Map<String, List<IMessageHandler>> topicHandlers = new ConcurrentHashMap<>();
private final ScheduledExecutorService reconnectExecutor = Executors.newSingleThreadScheduledExecutor();
private volatile boolean isConnecting;
private final ApplicationContext context;
public MqttTemplate(ApplicationContext context) {
this.context = context;
}
@PostConstruct
public void init() throws MqttException {
if (StringUtils.isBlank(clientId)) {
clientId = clientIdPrefix + UUID.randomUUID().toString().substring(0, 8);
}
client = new MqttAsyncClient(brokerUrl, clientId, new MemoryPersistence());
client.setCallback(this);
connect();
// autoRegisterHandlers();
}
@Override
public void destroy() throws Exception {
if (client != null && client.isConnected()) {
client.disconnect();
}
reconnectExecutor.shutdown();
}
/**
*
*
* @throws MqttException
*/
private void connect() throws MqttException {
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(cleanSession);
options.setConnectionTimeout(connectionTimeout);
options.setKeepAliveInterval(keepAliveInterval);
options.setAutomaticReconnect(false); // 手动控制重连
client.connect(options, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
log.info("MQTT连接成功");
resubscribeAllTopics();
autoRegisterHandlers();
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
log.error("初始连接失败", exception);
scheduleReconnect(1);
}
});
}
/**
*
* @param attempt
*/
private void scheduleReconnect(int attempt) {
if (attempt > maxReconnectAttempts) {
log.error("达到最大重连次数: {}", maxReconnectAttempts);
return;
}
long delay = (long) Math.min(1000 * Math.pow(2, attempt), 30000);
reconnectExecutor.schedule(() -> {
try {
log.info("尝试第{}次重连", attempt);
if (client != null && client.isConnected()) {
client.disconnectForcibly(); // 强制断开旧连接
client.close(true);
}
// 重新初始化客户端
client = new MqttAsyncClient(brokerUrl, clientId, new MemoryPersistence());
client.setCallback(this); // 关键:重新绑定回调
client.reconnect();
resubscribeAllTopics(); // 重连后立即订阅
log.info("重连成功");
} catch (MqttException e) {
log.error("重连失败", e);
scheduleReconnect(attempt + 1);
}
}, delay, TimeUnit.MILLISECONDS);
}
/**
*
* @param topic
* @param payload
* @param qos QoS
*/
@Async
public void publish(String topic, String payload, int qos) {
try {
if (!client.isConnected()) {
throw new MqttException(MqttException.REASON_CODE_CLIENT_NOT_CONNECTED);
}
client.publish(topic, payload.getBytes(), qos, false);
} catch (MqttException e) {
log.error("消息发送失败 [topic: {}]", topic, e);
}
}
@Async
public void publish(String topic, String payload) {
try {
if (!client.isConnected()) {
throw new MqttException(MqttException.REASON_CODE_CLIENT_NOT_CONNECTED);
}
client.publish(topic, payload.getBytes(), 1, false);
} catch (MqttException e) {
log.error("消息发送失败 [topic: {}]", topic, e);
}
}
/**
*
* @param topicFilter
* @param qos QoS
* @param handler
*/
public void subscribe(String topicFilter, int qos, IMessageHandler handler) {
try {
if (!client.isConnected()) {
log.warn("客户端未连接,延迟订阅 [topic: {}]", topicFilter);
return;
}
client.subscribe(topicFilter, qos);
topicHandlers.computeIfAbsent(topicFilter, k -> new ArrayList<>())
.add(handler);
log.info("订阅成功: {}", topicFilter);
} catch (MqttException e) {
log.error("订阅失败 [topic: {}]", topicFilter);
e.printStackTrace();
}
}
private void resubscribeAllTopics() {
topicHandlers.forEach((topic, handlers) -> {
int retry = 0;
while (retry < 3) {
try {
client.subscribe(topic, 1);
log.info("主题重新订阅成功: {}", topic);
break;
} catch (MqttException e) {
retry++;
log.error("重新订阅失败 [topic: {}], 重试 {}/3", topic, retry);
sleep(1000L * retry);
}
}
});
}
/**
*
* @param topic
* @param message
*/
@Override
public void messageArrived(String topic, MqttMessage message) {
topicHandlers.entrySet().stream()
.filter(entry -> MqttTopic.isMatched(entry.getKey(), topic))
.flatMap(entry -> entry.getValue().stream())
.forEach(handler -> {
try {
handler.handleMessage(topic, message);
} catch (Exception e) {
log.error("消息处理异常 [handler: {}]", handler.getClass(), e);
}
});
}
@Override
public void connectionLost(Throwable cause) {
log.error("连接丢失", cause);
scheduleReconnect(1);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// QoS处理逻辑
}
@Override
public void connectComplete(boolean reconnect, String serverURI) {
log.info("连接已建立 [reconnect: {}]", reconnect);
if (reconnect) {
resubscribeAllTopics();
autoRegisterHandlers();
}
}
/**
*
*/
private void autoRegisterHandlers() {
context.getBeansOfType(IMessageHandler.class).values()
.forEach(handler -> {
handler.getTopics().forEach(topic ->
subscribe(topic.getTopicFilter(), topic.getQos(), handler));
});
}
}