瀏覽代碼

数据推送

bihuisong 1 年之前
父節點
當前提交
80132bd610

二進制
InputStreamInfo.jpg


+ 74 - 0
src/main/java/com/sooka/sponest/dataexchange/exchange/conf/FeignConfig.java

@@ -0,0 +1,74 @@
+package com.sooka.sponest.dataexchange.exchange.conf;
+
+import com.sooka.sponest.dataexchange.exchange.domian.LoginBody;
+import feign.RequestInterceptor;
+import feign.RequestTemplate;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.Enumeration;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * @author echo lovely
+ * @date 2021/2/1 20:45
+ */
+@Configuration
+public class FeignConfig implements RequestInterceptor {
+    /**
+     * 复写feign请求对象
+     * @param requestTemplate hhh
+     */
+
+    @Override
+    public void apply(RequestTemplate requestTemplate) {
+        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
+                .getRequestAttributes();
+        if (attributes == null) {
+            return;
+        }
+        HttpServletRequest request = attributes.getRequest();
+        Enumeration<String> headerNames = request.getHeaderNames();
+        if (headerNames != null) {
+            while (headerNames.hasMoreElements()) {
+                String name = headerNames.nextElement();
+                String values = request.getHeader(name);
+                //跳过 content-length,避免追加参数导致content-length值与实际长度不一样
+                if (name.equals("content-length")) {
+                    continue;
+                }
+                Enumeration<String> values1 = request.getHeaders(name);
+                while (values1.hasMoreElements()) {
+                    String value = values1.nextElement();
+                    requestTemplate.header(name, value);
+                }
+            }
+        }
+    }
+    //获取请求对象
+    private HttpServletRequest getHttpServletRequest() {
+        try {
+            return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+    //拿到请求头信息
+    private Map<String, String> getHeaders(HttpServletRequest request) {
+        Map<String, String> map = new LinkedHashMap<>();
+        Enumeration<String> enumeration = request.getHeaderNames();
+        while (enumeration.hasMoreElements()) {
+            String key = enumeration.nextElement();
+            String value = request.getHeader(key);
+            map.put(key, value);
+        }
+        return map;
+    }
+
+}
+

+ 133 - 0
src/main/java/com/sooka/sponest/dataexchange/exchange/controller/ExchangeController.java

@@ -0,0 +1,133 @@
+package com.sooka.sponest.dataexchange.exchange.controller;
+
+
+import com.alibaba.fastjson.JSONObject;
+import com.ruoyi.common.core.domain.R;
+import com.ruoyi.common.core.web.domain.AjaxResult;
+import com.ruoyi.common.redis.service.RedisService;
+import com.sooka.sponest.dataexchange.exchange.domian.DataExchangeEntity;
+import com.sooka.sponest.dataexchange.exchange.domian.LoginBody;
+import com.sooka.sponest.dataexchange.exchange.utils.RestUtil;
+import com.sooka.sponest.dataexchange.remoteapi.service.center.auth.RemoteAuthBaseService;
+import com.sooka.sponest.dataexchange.remoteapi.service.center.event.RemoteEventBaseService;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.*;
+import springfox.documentation.spring.web.json.Json;
+
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+
+@Slf4j
+@Controller
+@RequestMapping("/data/exchange")
+public class ExchangeController {
+
+    @Resource
+    private RemoteAuthBaseService remoteAuthBaseService;
+    @Resource
+    private RemoteEventBaseService remoteEventBaseService;
+    @Resource
+    private RedisService redisService;
+
+
+    /**
+     * 获取秘钥接口
+     */
+    @PostMapping("/getRemoteSecretKey")
+    @ResponseBody
+    public R<?> getRemoteSecretKey() {
+        R<?> result = remoteAuthBaseService.getRemoteSecretKey();
+        if (result.getCode() == 200) {
+            return R.ok(result.getData().toString());
+        } else {
+            return R.fail();
+        }
+    }
+
+    /**
+     * 获取token
+     */
+    @PostMapping("/getToken")
+    @ResponseBody
+    public R<?> getToken(@RequestBody LoginBody form) {
+        R<?> result = remoteAuthBaseService.loginRemote(form);
+        if (result.getCode() == 200) {
+            Map<String, Object> json = (Map<String, Object>) result.getData();
+            return R.ok(json.get("access_token").toString());
+        } else {
+            return R.fail();
+        }
+    }
+
+    // TODO: 2024/1/6 0006 数据业务校验
+    @PostMapping("/dataCheck")
+    @ResponseBody
+    public R<?> dataCheck(@RequestBody List<DataExchangeEntity> list) {
+        boolean flag = list.stream()
+                .allMatch(item -> item.getId() != null && StringUtils.isNotEmpty(item.getName()));
+        if (flag) {
+            // TODO: 2024/1/6 0006  推送数据   调用event保存
+            R<?> result = remoteEventBaseService.saveDataExchangeEntity(list);
+            if (result.getCode() == 200) {
+                return R.ok();
+            } else {
+                return R.fail("事件存储失败");
+            }
+        } else {
+            return R.fail("验证失败");
+        }
+    }
+
+
+    // TODO: 2024/1/6 0006 订阅  被119调用  掉用event 更新redis缓存
+    @PostMapping("/subscribeTo")
+    @ResponseBody
+    public R<?> dataSubscribeTo() {
+        R<?> result = remoteEventBaseService.subscribeTo();
+        if (result.getCode() == 200) {
+            redisService.deleteObject("eventKey");
+            return R.ok();
+        } else {
+            return R.fail();
+        }
+    }
+
+    // TODO: 2024/1/6 0006  查询订阅    存redis中      推送119
+    @PostMapping("/pushData")
+    @ResponseBody
+    public R<?> pushData(@RequestBody List<DataExchangeEntity> list) {
+        JSONObject json = new JSONObject();
+        json.put("list", list);
+        if (redisService.hasKey("eventKey")) {
+            List<String> urlList = redisService.getCacheObject("eventKey");
+            try {
+                for (String var : urlList) {
+                    RestUtil.post(var, json);
+                }
+            } catch (Exception e) {
+                log.info("远程调用119报错");
+            }
+            return R.ok();
+        } else {
+            R<?> result = remoteEventBaseService.getDataSubscribeTo();
+            List<String> urlList = (List<String>) result.getData();
+            if (result.getCode() == 200) {
+                try {
+                    for (String var : urlList) {
+                        RestUtil.post(var, json);
+                    }
+                } catch (Exception e) {
+                    log.info("远程调用119报错");
+                }
+                redisService.setCacheList("eventKey", urlList);
+                return R.ok();
+            } else {
+                return R.fail("查询订阅失败");
+            }
+        }
+    }
+
+}

+ 16 - 0
src/main/java/com/sooka/sponest/dataexchange/exchange/domian/DataExchangeEntity.java

@@ -0,0 +1,16 @@
+package com.sooka.sponest.dataexchange.exchange.domian;
+
+
+import lombok.Data;
+
+@Data
+public class DataExchangeEntity {
+
+
+    private Long id;
+
+    private String name;
+
+
+
+}

+ 49 - 0
src/main/java/com/sooka/sponest/dataexchange/exchange/domian/LoginBody.java

@@ -0,0 +1,49 @@
+package com.sooka.sponest.dataexchange.exchange.domian;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * 用户登录对象
+ * 
+ * @author ruoyi
+ */
+@Getter
+@Setter
+public class LoginBody
+{
+    /**
+     * sessionId
+     */
+    private String sessionId;
+
+    /**
+     * 用户名
+     */
+    private String username;
+
+    /**
+     * 用户密码
+     */
+    private String password;
+
+    public String getUsername()
+    {
+        return username;
+    }
+
+    public void setUsername(String username)
+    {
+        this.username = username;
+    }
+
+    public String getPassword()
+    {
+        return password;
+    }
+
+    public void setPassword(String password)
+    {
+        this.password = password;
+    }
+}

+ 234 - 0
src/main/java/com/sooka/sponest/dataexchange/exchange/utils/RestUtil.java

@@ -0,0 +1,234 @@
+package com.sooka.sponest.dataexchange.exchange.utils;
+
+import com.alibaba.fastjson.JSONObject;
+import com.sooka.sponest.dataexchange.util.StringUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.*;
+import org.springframework.http.client.SimpleClientHttpRequestFactory;
+import org.springframework.http.converter.StringHttpMessageConverter;
+import org.springframework.web.client.RestTemplate;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * 调用 Restful 接口 Util
+ *
+ * @author bihs
+ */
+@Slf4j
+public class RestUtil {
+
+
+    /**
+     * RestAPI 调用器
+     */
+    private final static RestTemplate RT;
+
+    static {
+        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
+        requestFactory.setConnectTimeout(300000);
+        requestFactory.setReadTimeout(300000);
+        RT = new RestTemplate(requestFactory);
+        // 解决乱码问题
+        RT.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
+    }
+
+    public static RestTemplate getRestTemplate() {
+        return RT;
+    }
+
+    /**
+     * 发送 get 请求
+     */
+    public static JSONObject get(String url) {
+        return getNative(url, null, null).getBody();
+    }
+
+    /**
+     * 发送 get 请求
+     */
+    public static JSONObject get(String url, JSONObject variables) {
+        return getNative(url, variables, null).getBody();
+    }
+
+    /**
+     * 发送 get 请求
+     */
+    public static JSONObject get(String url, JSONObject variables, JSONObject params) {
+        return getNative(url, variables, params).getBody();
+    }
+
+    /**
+     * 发送 get 请求,返回原生 ResponseEntity 对象
+     */
+    public static ResponseEntity<JSONObject> getNative(String url, JSONObject variables, JSONObject params) {
+        return request(url, HttpMethod.GET, variables, params);
+    }
+
+    /**
+     * 发送 Post 请求
+     */
+    public static JSONObject post(String url) {
+        return postNative(url, null, null).getBody();
+    }
+
+    /**
+     * 发送 Post 请求
+     */
+    public static JSONObject post(String url, JSONObject params) {
+        return postNative(url, null, params).getBody();
+    }
+
+    /**
+     * 发送 Post 请求
+     */
+    public static JSONObject post(String url, JSONObject variables, JSONObject params) {
+        return postNative(url, variables, params).getBody();
+    }
+
+    /**
+     * 发送 POST 请求,返回原生 ResponseEntity 对象
+     */
+    public static ResponseEntity<JSONObject> postNative(String url, JSONObject variables, JSONObject params) {
+        return request(url, HttpMethod.POST, variables, params);
+    }
+
+    /**
+     * 发送 put 请求
+     */
+    public static JSONObject put(String url) {
+        return putNative(url, null, null).getBody();
+    }
+
+    /**
+     * 发送 put 请求
+     */
+    public static JSONObject put(String url, JSONObject params) {
+        return putNative(url, null, params).getBody();
+    }
+
+    /**
+     * 发送 put 请求
+     */
+    public static JSONObject put(String url, JSONObject variables, JSONObject params) {
+        return putNative(url, variables, params).getBody();
+    }
+
+    /**
+     * 发送 put 请求,返回原生 ResponseEntity 对象
+     */
+    public static ResponseEntity<JSONObject> putNative(String url, JSONObject variables, JSONObject params) {
+        return request(url, HttpMethod.PUT, variables, params);
+    }
+
+    /**
+     * 发送 delete 请求
+     */
+    public static JSONObject delete(String url) {
+        return deleteNative(url, null, null).getBody();
+    }
+
+    /**
+     * 发送 delete 请求
+     */
+    public static JSONObject delete(String url, JSONObject variables, JSONObject params) {
+        return deleteNative(url, variables, params).getBody();
+    }
+
+    /**
+     * 发送 delete 请求,返回原生 ResponseEntity 对象
+     */
+    public static ResponseEntity<JSONObject> deleteNative(String url, JSONObject variables, JSONObject params) {
+        return request(url, HttpMethod.DELETE, null, variables, params, JSONObject.class);
+    }
+
+    /**
+     * 发送请求
+     */
+    public static ResponseEntity<JSONObject> request(String url, HttpMethod method, JSONObject variables, JSONObject params) {
+        return request(url, method, getHeaderApplicationJson(), variables, params, JSONObject.class);
+    }
+
+    /**
+     * 发送请求
+     *
+     * @param url          请求地址
+     * @param method       请求方式
+     * @param headers      请求头  可空
+     * @param variables    请求url参数 可空
+     * @param params       请求body参数 可空
+     * @param responseType 返回类型
+     * @return ResponseEntity<responseType>
+     */
+    public static <T> ResponseEntity<T> request(String url, HttpMethod method, HttpHeaders headers, JSONObject variables, Object params, Class<T> responseType) {
+        log.info(" RestUtil  --- request ---  url = "+ url);
+        if (StringUtils.isEmpty(url)) {
+            throw new RuntimeException("url 不能为空");
+        }
+        if (method == null) {
+            throw new RuntimeException("method 不能为空");
+        }
+        if (headers == null) {
+            headers = new HttpHeaders();
+        }
+        // 请求体
+        String body = "";
+        if (params != null) {
+            if (params instanceof JSONObject) {
+                body = ((JSONObject) params).toJSONString();
+
+            } else {
+                body = params.toString();
+            }
+        }
+        // 拼接 url 参数
+        if (variables != null) {
+            url += ("?" + asUrlVariables(variables));
+        }
+        // 发送请求
+        HttpEntity<String> request = new HttpEntity<>(body, headers);
+        return RT.exchange(url, method, request, responseType);
+    }
+
+    /**
+     * 获取JSON请求头
+     */
+    public static HttpHeaders getHeaderApplicationJson() {
+        return getHeader(MediaType.APPLICATION_JSON_UTF8_VALUE);
+    }
+
+    /**
+     * 获取请求头
+     */
+    public static HttpHeaders getHeader(String mediaType) {
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.parseMediaType(mediaType));
+        headers.add("Accept", mediaType);
+        return headers;
+    }
+
+    /**
+     * 将 JSONObject 转为 a=1&b=2&c=3...&n=n 的形式
+     */
+    public static String asUrlVariables(JSONObject variables) {
+        Map<String, Object> source = variables.getInnerMap();
+        Iterator<String> it = source.keySet().iterator();
+        StringBuilder urlVariables = new StringBuilder();
+        while (it.hasNext()) {
+            String key = it.next();
+            String value = "";
+            Object object = source.get(key);
+            if (object != null) {
+                if (!StringUtils.isEmpty(object.toString())) {
+                    value = object.toString();
+                }
+            }
+            urlVariables.append("&").append(key).append("=").append(value);
+        }
+        // 去掉第一个&
+        return urlVariables.substring(1);
+    }
+
+}

+ 38 - 0
src/main/java/com/sooka/sponest/dataexchange/remoteapi/fallback/center/auth/RemoteAuthBaseServiceFallbackFactory.java

@@ -0,0 +1,38 @@
+package com.sooka.sponest.dataexchange.remoteapi.fallback.center.auth;
+
+
+import com.ruoyi.common.core.domain.R;
+import com.sooka.sponest.dataexchange.exchange.domian.LoginBody;
+import com.sooka.sponest.dataexchange.remoteapi.service.center.auth.RemoteAuthBaseService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.cloud.openfeign.FallbackFactory;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+
+
+@Component
+public class RemoteAuthBaseServiceFallbackFactory implements FallbackFactory<RemoteAuthBaseService> {
+    private static final Logger log = LoggerFactory.getLogger(RemoteAuthBaseServiceFallbackFactory.class);
+
+    @Override
+    public RemoteAuthBaseService create(Throwable cause) {
+        log.error("认证中心-服务调用失败:{}", cause.getMessage());
+
+
+        return new RemoteAuthBaseService() {
+
+            @Override
+            public R<?> loginRemote(LoginBody form) {
+                return null;
+            }
+
+            @Override
+            public R<?> getRemoteSecretKey() {
+                return null;
+            }
+
+        };
+    }
+}

+ 43 - 0
src/main/java/com/sooka/sponest/dataexchange/remoteapi/fallback/center/event/RemoteEventBaseServiceFallbackFactory.java

@@ -0,0 +1,43 @@
+package com.sooka.sponest.dataexchange.remoteapi.fallback.center.event;
+
+
+import com.ruoyi.common.core.domain.R;
+import com.sooka.sponest.dataexchange.exchange.domian.DataExchangeEntity;
+import com.sooka.sponest.dataexchange.exchange.domian.LoginBody;
+import com.sooka.sponest.dataexchange.remoteapi.service.center.auth.RemoteAuthBaseService;
+import com.sooka.sponest.dataexchange.remoteapi.service.center.event.RemoteEventBaseService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.cloud.openfeign.FallbackFactory;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+
+
+@Component
+public class RemoteEventBaseServiceFallbackFactory implements FallbackFactory<RemoteEventBaseService> {
+    private static final Logger log = LoggerFactory.getLogger(RemoteEventBaseServiceFallbackFactory.class);
+
+    @Override
+    public RemoteEventBaseService create(Throwable cause) {
+        log.error("事件中心-服务调用失败:{}", cause.getMessage());
+
+        return new RemoteEventBaseService() {
+
+            @Override
+            public R<?> saveDataExchangeEntity(List<DataExchangeEntity> list) {
+                return null;
+            }
+
+            @Override
+            public R<?> subscribeTo() {
+                return null;
+            }
+
+            @Override
+            public R<?> getDataSubscribeTo() {
+                return null;
+            }
+        };
+    }
+}

+ 3 - 0
src/main/java/com/sooka/sponest/dataexchange/remoteapi/service/ModulesServiceNameContants.java

@@ -43,4 +43,7 @@ public class ModulesServiceNameContants extends ServiceNameConstants {
      */
     public static final String SYSTEM_SERVICE = "sooka-sponest-system";
 
+    //认证中心
+    public static final String CENTER_AUTH = "sooka-sponest-auth";
+
 }

+ 28 - 0
src/main/java/com/sooka/sponest/dataexchange/remoteapi/service/center/auth/RemoteAuthBaseService.java

@@ -0,0 +1,28 @@
+package com.sooka.sponest.dataexchange.remoteapi.service.center.auth;
+
+
+import com.ruoyi.common.core.domain.R;
+import com.sooka.sponest.dataexchange.exchange.domian.LoginBody;
+import com.sooka.sponest.dataexchange.remoteapi.fallback.center.auth.RemoteAuthBaseServiceFallbackFactory;
+import com.sooka.sponest.dataexchange.remoteapi.service.ModulesServiceNameContants;
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.Map;
+
+
+@FeignClient(
+        contextId = "RemoteAuthBaseService",
+        value = ModulesServiceNameContants.CENTER_AUTH,
+        fallbackFactory = RemoteAuthBaseServiceFallbackFactory.class,
+        url = "${sooka.service.auth}"
+)
+public interface RemoteAuthBaseService {
+
+    @PostMapping("/loginRemote")
+    public R<?> loginRemote(LoginBody form);
+
+    @PostMapping("/getRemoteSecretKey")
+    public R<?> getRemoteSecretKey();
+
+}

+ 34 - 0
src/main/java/com/sooka/sponest/dataexchange/remoteapi/service/center/event/RemoteEventBaseService.java

@@ -0,0 +1,34 @@
+package com.sooka.sponest.dataexchange.remoteapi.service.center.event;
+
+
+import com.ruoyi.common.core.domain.R;
+import com.sooka.sponest.dataexchange.exchange.domian.DataExchangeEntity;
+import com.sooka.sponest.dataexchange.exchange.domian.LoginBody;
+import com.sooka.sponest.dataexchange.remoteapi.fallback.center.auth.RemoteAuthBaseServiceFallbackFactory;
+import com.sooka.sponest.dataexchange.remoteapi.fallback.center.event.RemoteEventBaseServiceFallbackFactory;
+import com.sooka.sponest.dataexchange.remoteapi.service.ModulesServiceNameContants;
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.PostMapping;
+
+import java.util.List;
+
+
+@FeignClient(
+        contextId = "RemoteEventBaseService",
+        value = ModulesServiceNameContants.CENTER_EVENT,
+        fallbackFactory = RemoteEventBaseServiceFallbackFactory.class,
+        url = "${sooka.service.event}"
+)
+public interface RemoteEventBaseService {
+
+    @PostMapping("/saveDataExchangeEntity")
+    public R<?> saveDataExchangeEntity(List<DataExchangeEntity> list);
+
+    @PostMapping("/subscribeTo")
+    public R<?> subscribeTo();
+
+
+    @PostMapping("/getDataSubscribeTo")
+    public R<?> getDataSubscribeTo();
+
+}

+ 4 - 4
src/main/resources/bootstrap.yml

@@ -14,12 +14,12 @@ spring:
     nacos:
       discovery:
         # 服务注册地址
-#        server-addr: www.sooka.onest.com:8848
-        server-addr: 127.0.0.1:8848
+        server-addr: www.sooka.onest.com:8848
+#        server-addr: 127.0.0.1:8848
       config:
         # 配置中心地址
-#        server-addr: www.sooka.onest.com:8848
-        server-addr: 127.0.0.1:8848
+        server-addr: www.sooka.onest.com:8848
+#        server-addr: 127.0.0.1:8848
         # 配置文件格式
         file-extension: yml
         # 共享配置