mitao
2024-05-27 c26092c422c4b72fa5d51a38f6de1b48ab1ccd87
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package com.ruoyi.goods.service.impl;
 
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.enums.ListingStatusEnum;
import com.ruoyi.common.core.enums.StartStatusEnum;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.page.BeanUtils;
import com.ruoyi.common.core.utils.page.PageDTO;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.goods.controller.management.dto.GoodsSeckillDTO;
import com.ruoyi.goods.controller.management.dto.GoodsSeckillQuery;
import com.ruoyi.goods.controller.management.dto.GoodsSeckillUpd;
import com.ruoyi.goods.controller.management.vo.GoodsSeckillVO;
import com.ruoyi.goods.mapper.GoodsSeckillMapper;
import com.ruoyi.goods.service.IGoodsSeckillService;
import com.ruoyi.goods.service.IGoodsSkuService;
import com.ruoyi.goods.service.async.AsyncMethodService;
import com.ruoyi.system.api.constants.DelayTaskEnum;
import com.ruoyi.system.api.constants.NotificationTypeConstant;
import com.ruoyi.system.api.domain.GoodsSeckill;
import com.ruoyi.system.api.domain.GoodsSku;
import com.ruoyi.system.api.domain.dto.ListStatusDTO;
import com.ruoyi.system.api.feignClient.OrderClient;
import com.ruoyi.system.api.feignClient.SysUserClient;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.WebSocketUsers;
 
/**
 * <p>
 * 商品秒杀表 服务实现类
 * </p>
 *
 * @author mitao
 * @since 2024-05-16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GoodsSeckillServiceImpl extends ServiceImpl<GoodsSeckillMapper, GoodsSeckill> implements IGoodsSeckillService {
 
    private final IGoodsSkuService goodsSkuService;
    private final OrderClient orderClient;
    private final RedisService redisService;
    private final SysUserClient sysUserClient;
    private final AsyncMethodService asyncMethodService;
    // 创建一个静态共享的ObjectMapper实例以重用
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addGoodsSeckill(GoodsSeckillDTO dto) {
        List<GoodsSeckill> goodsSeckills = BeanUtils.copyList(dto.getGoodsSkuList(),
                GoodsSeckill.class);
        for (GoodsSeckill goodsSeckill : goodsSeckills) {
            goodsSeckill.setShareTitle(dto.getShareTitle());
            goodsSeckill.setSharePic(dto.getSharePic());
            goodsSeckill.setStartTime(dto.getStartTime());
            goodsSeckill.setEndTime(dto.getEndTime());
            goodsSeckill.setStartStatus(StartStatusEnum.NOT_STARTED);
        }
        this.saveBatch(goodsSeckills);
 
        for (GoodsSeckill goodsSeckill : goodsSeckills) {
            GoodsSku goodsSku = goodsSkuService.getById(goodsSeckill.getGoodsSkuId());
            if (StringUtils.isNull(goodsSku)) {
                throw new ServiceException("商品不存在");
            }
            Integer seckillStock = goodsSeckill.getSeckillStock();
            goodsSkuService.lambdaUpdate()
                    .set(GoodsSku::getStock, goodsSku.getStock() - seckillStock)
                    .ge(GoodsSku::getStock, seckillStock)
                    .eq(GoodsSku::getId, goodsSku.getId());
            asyncMethodService.seckillScheduleTask(goodsSeckill);
        }
    }
 
 
    /**
     * 获取秒杀商品列表的分页数据
     *
     * @param query 秒杀商品查询对象
     * @return PageDTO<GoodsSeckillVO>
     */
    @Override
    public PageDTO<GoodsSeckillVO> getGoodsSeckillPage(GoodsSeckillQuery query) {
        return PageDTO.of(baseMapper.getGoodsSeckillPage(query.getGoodsSkuName(),
                new Page<>(query.getPageCurr(), query.getPageSize())
        ));
    }
 
    /**
     * 修改秒杀商品
     *
     * @param upd 商品秒杀数据传输对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updGoodsSeckill(GoodsSeckillUpd upd) {
        //查询秒杀商品
        GoodsSeckill goodsSeckill = this.getById(upd.getId());
        if (StringUtils.isNull(goodsSeckill)) {
            throw new ServiceException("秒杀商品不存在");
        }
        if (goodsSeckill.getStartStatus().equals(StartStatusEnum.STARTED)) {
            throw new ServiceException("秒杀商品已开始秒杀,不能修改");
        }
        GoodsSeckill goodsSeckillUpd = BeanUtils.copyBean(upd, GoodsSeckill.class);
        this.updateById(goodsSeckillUpd);
        asyncMethodService.seckillScheduleTask(goodsSeckill);
    }
 
    /**
     * 上架/下架 秒杀商品
     *
     * @param dto 商品上下架状态对象
     */
    @Override
    public void updStatus(ListStatusDTO dto) {
        GoodsSeckill goodsSeckill = this.getById(dto.getId());
        if (StringUtils.isNull(goodsSeckill)) {
            throw new ServiceException("秒杀商品不存在");
        }
        this.lambdaUpdate()
                .eq(GoodsSeckill::getId, dto.getId())
                .set(GoodsSeckill::getListingStatus, dto.getListingStatus())
                .update();
        if (dto.getListingStatus().equals(ListingStatusEnum.REMOVED_FROM_THE_SHELF)) {
            //移除该秒杀商品的延时任务
            redisService.deleteObject(
                    DelayTaskEnum.SECKILL_START_TASK.getCode() + "-" + goodsSeckill.getId());
            redisService.deleteObject(
                    DelayTaskEnum.SECKILL_END_TASK.getCode() + "-" + goodsSeckill.getId());
        }
    }
 
    /**
     * 查看详情
     *
     * @param id 秒杀商品id
     * @return GoodsSeckillVO 商品秒杀视图对象
     */
    @Override
    public GoodsSeckillVO getDetail(Long id) {
        GoodsSeckill goodsSeckill = this.getById(id);
        if (StringUtils.isNull(goodsSeckill)) {
            throw new ServiceException("秒杀商品不存在");
        }
        GoodsSeckillVO vo = BeanUtils.copyBean(goodsSeckill, GoodsSeckillVO.class);
        GoodsSku goods = goodsSkuService.getById(goodsSeckill.getGoodsSkuId());
        Optional.of(goods).ifPresent(goodsSku -> vo.setGoodsSkuName(goodsSku.getSkuName()));
        Integer num = orderClient.getSeckillMembers(goodsSeckill.getGoodsSkuId()).getData();
        vo.setNumberOfPurchasedMembers(num);
        return vo;
    }
 
    /**
     * 开始秒杀
     *
     * @param seckillId 秒杀id
     */
    @Override
    public void startSeckill(Long seckillId) throws JsonProcessingException {
        log.info(">>>>>>>>>>>>>>>>>>>>{}秒杀开始<<<<<<<<<<<<<<<<<<<<", seckillId);
        GoodsSeckill goodsSeckill = this.getById(seckillId);
        //秒杀商品不能为空且状态为未开始
        if (StringUtils.isNotNull(goodsSeckill)
                && goodsSeckill.getStartStatus().equals(StartStatusEnum.NOT_STARTED)) {
            //开始秒杀
            this.lambdaUpdate().set(GoodsSeckill::getStartStatus, StartStatusEnum.STARTED)
                    .eq(GoodsSeckill::getId, seckillId).update();
//            将秒杀商品放入缓存
            redisService.setCacheObject(
                    CacheConstants.SECKILL_GOODS + goodsSeckill.getId(),
                    goodsSeckill.getSeckillStock());
        }
        //推送秒杀开始消息
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("notification_type", NotificationTypeConstant.SECKILL);
        map.put("notification_time", LocalDateTime.now());
        map.put("message_type", "start");
        String msg = objectMapper.writeValueAsString(map);
        WebSocketUsers.sendMessageToUsersByText(msg);
        log.info("===================>发送websocket通知,消息体{}", msg);
    }
 
    /**
     * 结束秒杀
     *
     * @param seckillId 秒杀id
     */
    @Override
    public void endSeckill(Long seckillId) throws JsonProcessingException {
        log.info(">>>>>>>>>>>>>>>>>>>>{}秒杀结束<<<<<<<<<<<<<<<<<<<<", seckillId);
        GoodsSeckill goodsSeckill = this.getById(seckillId);
        if (StringUtils.isNotNull(goodsSeckill)
                && goodsSeckill.getStartStatus().equals(StartStatusEnum.STARTED)) {
            //结束秒杀
            this.lambdaUpdate().set(GoodsSeckill::getStartStatus, StartStatusEnum.ENDED)
                    .eq(GoodsSeckill::getId, seckillId).update();
//            将秒杀商品从缓存中移除
            redisService.deleteObject(CacheConstants.SECKILL_GOODS + goodsSeckill.getId());
        }
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("notification_type", NotificationTypeConstant.SECKILL);
        map.put("notification_time", LocalDateTime.now());
        map.put("message_type", "end");
        String msg = objectMapper.writeValueAsString(map);
        WebSocketUsers.sendMessageToUsersByText(msg);
        log.info("===================>发送websocket通知,消息体{}", msg);
    }
}