严智鑫
2024-03-18 d812f6f23b3f0e4ad6cd140341b494275b628ee3
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
package com.example.springboot.controller;
 
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.example.springboot.common.MessageSender;
import com.example.springboot.component.RabbitMQUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
 
import com.example.springboot.common.MessageSender.Person;
 
@RestController
public class MessageController {
 
    @Autowired
    private MessageSender messageSender;
 
    @GetMapping("/send/{message}")
    public String sendMessage(@PathVariable("message") String message) {
        messageSender.sendMessage(message);
        return "Message sent: " + message;
    }
 
    @GetMapping("/sendPerson/{name}/{age}")
    public String sendPersonMessage(@PathVariable("name") String name, @PathVariable("age") int age) {
        Person person = new Person(name, age);
        messageSender.sendMessage2(person);
        return "Person message sent: " + person;
    }
 
    @GetMapping("/sendJson")
    public String sendJsonMessage() {
        // 创建要发送的对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key1", "value1");
        jsonObject.put("key2", 123);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add("item1");
        jsonArray.add("item2");
        jsonObject.put("key3", jsonArray);
 
 
        try {
            // 调用 RabbitMQUtils 发送 JSON 消息的方法
            RabbitMQUtils.sendJsonMessage(jsonObject, "yourQueueName");
            return "JSON message sent: " + jsonObject;
        } catch (Exception e) {
            return "Failed to send JSON message: " + e.getMessage();
        }
 
    }
 
}