1
13693261870
2024-12-30 2d8dc64971a203e5cb2485bf1714892a8005fc0f
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
package com.se.system.service;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.se.system.domain.vo.NacosConfigVo;
import com.se.system.utils.CaffeineUtils;
import com.se.system.utils.StringUtils;
import nonapi.io.github.classgraph.json.JSONUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Map;
 
@Component
@SuppressWarnings("ALL")
public class NacosService {
    @Value("${spring.cloud.nacos.config.server-addr}")
    String serverAddr;
 
    @Value("${spring.cloud.nacos.username}")
    String username;
 
    @Value("${spring.cloud.nacos.password}")
    String password;
 
    @Resource
    RestTemplate restTemplate;
 
    final static String key = "nacos:login:token";
 
    private String getToken() throws Exception {
        Object obj = CaffeineUtils.get(key);
        if (obj instanceof String) {
            return (String) obj;
        }
 
        String token = login();
        if (null == token) throw new Exception("Nacos令牌为空");
 
        CaffeineUtils.put(key, token);
 
        return token;
    }
 
    private String login() {
        String url = "http://" + serverAddr + "/nacos/v1/auth/users/login";
 
        MultiValueMap<String, Object> map = new LinkedMultiValueMap();
        map.add("username", username);
        map.add("password", password);
 
        JSONObject obj = restTemplate.postForObject(url, map, JSONObject.class);
        if (null == obj || !obj.containsKey("accessToken")) {
            return null;
        }
 
        return obj.getString("accessToken");
    }
 
    public void getNacosConfig(String dataId, HttpServletRequest req, HttpServletResponse res) throws Exception {
        String token = getToken();
        // String url = "http://" + serverAddr + "/nacos/v1/cs/configs?dataId=" + dataId + "&group=&appName=&pageNo=1&pageSize=10&search=accurate";
        String url = "http://" + serverAddr + "/nacos/v1/cs/configs?dataId=" + dataId + "&group=DEFAULT_GROUP&namespaceId=&tenant=&show=all&username=";
 
        HttpHeaders headers = new HttpHeaders();
        headers.set("accessToken", token);
 
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(headers);
        ResponseEntity<String> re = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
 
        res.setContentType("application/json;charset=UTF-8");
        PrintWriter out = res.getWriter();
        out.print(re.getBody());
        out.flush();
        out.close();
    }
 
    public void updateNacosConfig(NacosConfigVo vo, HttpServletRequest req, HttpServletResponse res) throws Exception {
        if (null == vo || null == vo.getId() || null == vo.getDataId() || null == vo.getContent())
            throw new Exception("NacosConfigVo数据不正确");
 
        String token = getToken();
        vo.setModifyTime(System.currentTimeMillis());
        //vo.setMd5(StringUtils.md5(vo.getContent()));
        String url = "http://" + serverAddr + "/nacos/v1/cs/configs?username=" + username;
 
        HttpHeaders headers = new HttpHeaders();
        // headers.setContentType(MediaType.APPLICATION_JSON);
        // headers.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));
        headers.setContentType(MediaType.valueOf("application/x-www-form-urlencoded"));
        headers.set("accessToken", token);
        headers.set("casMd5", vo.getMd5());
 
        MultiValueMap<String, Object> map = createMap(vo);
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
        ResponseEntity<String> re = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
 
        res.setContentType("application/json;charset=UTF-8");
        PrintWriter out = res.getWriter();
        out.print(re.getBody());
        out.flush();
        out.close();
    }
 
    private <T> MultiValueMap<String, Object> createMap(T t) throws Exception {
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
 
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.add(field.getName(), field.get(t));
        }
 
        return map;
    }
}