yaowanxin
2 天以前 d5e714fecf9cba48c1a225e6eb53078cdad647c7
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
package com.ruoyi.device.controller;
 
 
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.device.constant.DCResistanceMqttConstants;
import com.ruoyi.device.dto.WeightRequestDto;
import org.springframework.http.ResponseEntity;
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 java.util.List;
 
 
@RestController
@RequestMapping("/weight")
public class WeightController {
 
    @PostMapping("/handleWeights")
    public ResponseEntity<String> handleWeights(@RequestBody WeightRequestDto weightRequest) {
        try {
            List<Double> weightList = weightRequest.getWeights();
            // 在这里添加数据处理逻辑,例如打印、存储到数据库等
            System.out.println("接收到的数据: " + weightList);
            processThreeTimesValueDataStream(weightList, WeightRequestDto.DENSITY);
 
            // 处理成功返回 200 状态码和消息
            return ResponseEntity.ok("数据处理成功");
        } catch (Exception e) {
            // 处理失败返回 500 状态码和错误消息
            return ResponseEntity.internalServerError().body("数据处理失败: " + e.getMessage());
        }
    }
 
    private void processThreeTimesValueDataStream(List<Double> weightList, String dataStream) {
        // 从 Redis 获取已存储的值
        Object valueFromRedis = RedisUtil.get(dataStream);
        JSONArray valueArray = new JSONArray();
 
 
        if (valueFromRedis != null) {
            if (valueFromRedis instanceof String) {
                try {
                    valueArray = JSONArray.parseArray((String) valueFromRedis);
                } catch (Exception e) {
                    // 如果解析失败,说明 Redis 中的值可能不是合法的 JSON 数组,创建空数组
                    valueArray = new JSONArray();
                }
            } else if (valueFromRedis instanceof Double) {
                valueArray.add(valueFromRedis);
            }
        }
        valueArray.addAll(weightList);
        RedisUtil.set(dataStream, valueArray.toJSONString());
    }
}