admin
2019-04-26 8e30aa7c1f0384f09278699318b4902b815b42a7
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
package com.yeshi.fanli.util.cmq;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.yeshi.utils.CMQUtil;
 
import com.google.gson.Gson;
import com.qcloud.cmq.Message;
import com.yeshi.fanli.entity.bus.user.ThreeSale;
import com.yeshi.fanli.log.LogHelper;
 
public class ThreeSaleCMQManager {
 
    private static String secretId = "AKIDTlpgJhLjOozvd6QI2XnpfGbgV4NQJk25";
    private static String secretKey = "xhCSUHo55oHUQ6XicFcmfIgspX0EEzWo";
    private static ThreeSaleCMQManager threeSaleCMQManager;
    private static CMQUtil cmqUtil;
 
    private final static String TOPIC_NAME = "topic_three_sale";
 
    public static String QUEUE_USER_COUPON = TOPIC_NAME + "_" + "user_coupon";
 
    public static String SUBSCRIBE_USER_COUPON = "user_coupon";
 
    static {
        cmqUtil = CMQUtil.getInstance(secretId, secretKey);
        // 创建主题,添加订阅
        cmqUtil.createTopic(TOPIC_NAME);
        // 用户券订阅
        String[] subscripts = new String[] { SUBSCRIBE_USER_COUPON };
        String[] queues = new String[] { QUEUE_USER_COUPON };
 
        for (int i = 0; i < subscripts.length; i++) {
            String queueName = queues[i];
            cmqUtil.createQueue(queueName);
            cmqUtil.subscribeTopic(TOPIC_NAME, subscripts[i], queueName);
        }
    }
 
    public static ThreeSaleCMQManager getInstance() {
        if (threeSaleCMQManager == null)
            threeSaleCMQManager = new ThreeSaleCMQManager();
        return threeSaleCMQManager;
    }
 
    /**
     * 发布
     * 
     * @param history
     */
    public void addThreeSaleMsg(ThreeSale threeSale) {
        if (threeSale == null)
            return;
        cmqUtil.publishTopicMessage(TOPIC_NAME, new Gson().toJson(threeSale));
        LogHelper.test("邀请消息投递成功");
    }
 
    /**
     * 消费队列消息
     * 
     * @param queueName
     * @param count
     * @return
     */
    public Map<String, ThreeSale> consumeQueueMsg(String queueName, int count) {
        List<Message> list = cmqUtil.recieveMsg(count, queueName);
        Map<String, ThreeSale> map = new HashMap<>();
 
        if (list != null)
            for (Message msg : list) {
                String result = msg.msgBody;
                ThreeSale threeSale = new Gson().fromJson(result, ThreeSale.class);
                map.put(msg.receiptHandle, threeSale);
            }
        return map;
    }
 
    public void deleteQueueMsg(String queueName, String receiptHandle) {
        cmqUtil.deleteMsg(queueName, receiptHandle);
    }
 
}