package com.se.system.service;
|
|
import com.alibaba.fastjson.JSONObject;
|
import com.se.system.utils.CaffeineUtils;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.http.HttpEntity;
|
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpMethod;
|
import org.springframework.http.ResponseEntity;
|
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.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() {
|
Object obj = CaffeineUtils.get(key);
|
if (obj instanceof String) {
|
return (String) obj;
|
}
|
|
String token = login();
|
if (null != token) {
|
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();
|
if (null == token) throw new Exception("Nacos令牌为空");
|
|
String url = "http://" + serverAddr + "/nacos/v1/cs/configs?dataId=se-system-dev.yml&group=&appName=&pageNo=1&pageSize=10&search=accurate";
|
|
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();
|
}
|
}
|