Parcourir la source

实现职能信息同步

欧阳劲驰 il y a 1 semaine
Parent
commit
4752210914

+ 120 - 11
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/components/InfoSynchronizer.java

@@ -1,6 +1,8 @@
 package com.shkpr.service.customgateway.zydma.components;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
 import com.global.base.log.LogLevelFlag;
 import com.global.base.log.LogPrintMgr;
 import com.shkpr.service.customgateway.core.constants.LogFlagBusiType;
@@ -9,20 +11,20 @@ import com.shkpr.service.customgateway.core.exception.SelfException;
 import com.shkpr.service.customgateway.core.properties.CallingProperties;
 import com.shkpr.service.customgateway.core.utils.CallingUtil;
 import com.shkpr.service.customgateway.zydma.constants.MiddlePlatformMetadata;
-import com.shkpr.service.customgateway.zydma.domain.MiddlePlatformPage;
-import com.shkpr.service.customgateway.zydma.domain.MiddlePlatformResult;
-import com.shkpr.service.customgateway.zydma.domain.MiddlePlatformUser;
+import com.shkpr.service.customgateway.zydma.domain.*;
+import com.shkpr.service.customgateway.zydma.domain.po.FunctionInfo;
 import com.shkpr.service.customgateway.zydma.domain.po.PersonnelInfo;
+import com.shkpr.service.customgateway.zydma.service.FunctionInfoService;
 import com.shkpr.service.customgateway.zydma.service.PersonnelInfoService;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.http.Header;
 import org.apache.http.message.BasicHeader;
 import org.springframework.http.HttpMethod;
 import org.springframework.stereotype.Component;
 
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
+import java.util.*;
+import java.util.function.Consumer;
+import java.util.function.Function;
 import java.util.stream.Collectors;
 
 /**
@@ -43,13 +45,19 @@ public class InfoSynchronizer {
     final
     CallingProperties callingProperties;
     final
+    ObjectMapper objectMapper;
+    final
     PersonnelInfoService personnelInfoService;
     final
+    FunctionInfoService functionInfoService;
+    final
     CallingUtil callingUtil;
 
-    public InfoSynchronizer(CallingProperties callingProperties, PersonnelInfoService personnelInfoService, CallingUtil callingUtil) {
+    public InfoSynchronizer(CallingProperties callingProperties, ObjectMapper objectMapper, PersonnelInfoService personnelInfoService, FunctionInfoService functionInfoService, CallingUtil callingUtil) {
         this.callingProperties = callingProperties;
+        this.objectMapper = objectMapper;
         this.personnelInfoService = personnelInfoService;
+        this.functionInfoService = functionInfoService;
         this.callingUtil = callingUtil;
     }
 
@@ -69,13 +77,23 @@ public class InfoSynchronizer {
         //获取用户
         List<MiddlePlatformUser> users = getUsers(endpoint);
 
-        //遍历用户
-        //todo 用户角色信息获取
-
         //转换用户对象
         List<PersonnelInfo> dates = users.stream()
                 .map(MiddlePlatformUser::toPersonnelInfo).collect(Collectors.toList());
 
+        //遍历用户,并设置职能信息
+        dates.forEach(personnelInfo -> {
+            List<String> ids = getRoles(endpoint, personnelInfo.getUid()).stream().map(MiddlePlatformRole::getRoleId).collect(Collectors.toList());
+            try {
+                personnelInfo.setPostId(objectMapper.writeValueAsString(ids));
+            } catch (JsonProcessingException e) {
+                LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR, BIZ_TYPE, CLASS_NAME
+                        , String.format("职能id集合json序列化失败 error:%s", e)
+                );
+            }
+        });
+
+
         //批量写入用户
         Boolean upserted = personnelInfoService.upsertAll(dates);
         long end = System.currentTimeMillis();
@@ -89,6 +107,37 @@ public class InfoSynchronizer {
     }
 
     /**
+     * 同步职能信息
+     *
+     */
+    public void syncFunctionInfo() {
+        LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_INFO, BIZ_TYPE, CLASS_NAME
+                , "开始同步职能信息,开始拉取数据");
+        long begin = System.currentTimeMillis();
+
+        //对接点
+        CallingProperties.CallingEndpoint endpoint = callingProperties.getEndpoints().get(MiddlePlatformMetadata.NAME);
+
+        //获取角色
+        List<MiddlePlatformRole> roles = getRoles(endpoint, null);
+
+        //转换职能对象
+        List<FunctionInfo> dates = roles.stream()
+                .map(MiddlePlatformRole::toFunctionInfo).collect(Collectors.toList());
+
+        //批量写入职能
+        Boolean upserted = functionInfoService.upsertAll(dates);
+        long end = System.currentTimeMillis();
+        LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_INFO, BIZ_TYPE, CLASS_NAME
+                , String.format(
+                        "结束执行同步职能信息,迁移状态:%s,用时(毫秒):%d"
+                        , upserted
+                        , (end - begin)
+                )
+        );
+    }
+
+    /**
      * 获取用户
      *
      * @param endpoint 对接点
@@ -121,4 +170,64 @@ public class InfoSynchronizer {
             return Collections.emptyList();
         }
     }
+
+    /**
+     * 获取角色
+     *
+     * @param endpoint 对接点
+     * @param userId   用户id
+     * @return 角色列表
+     */
+    public List<MiddlePlatformRole> getRoles(CallingProperties.CallingEndpoint endpoint, String userId) {
+        //结果
+        List<MiddlePlatformRole> result = new ArrayList<>();
+        //请求地址
+        String url = endpoint.getUrl() + MiddlePlatformMetadata.Uri.ROLE_GROUP_LIST;
+        //参数
+        Map<String, String> params = Collections.singletonMap(MiddlePlatformMetadata.Params.USER_ID, (userId != null ? userId : "-1"));
+        //密钥
+        IntegrationKey key = MiddlePlatformMetadata.getKey(endpoint.getAccessKey(), endpoint.getSecretKey(), params);
+        //请求头
+        List<Header> headers = Arrays.asList(
+                new BasicHeader(MiddlePlatformMetadata.Headers.APP_KEY, key.getAccessKey()),
+                new BasicHeader(MiddlePlatformMetadata.Headers.TIMESTAMP, key.getTimestamp() + ""),
+                new BasicHeader(MiddlePlatformMetadata.Headers.SIGN, key.getSecretKey())
+        );
+
+        //请求结果项
+        Map<String, List<MiddlePlatformSubsystem>> items = Collections.emptyMap();
+        try {
+            items = callingUtil.requestObject(url, HttpMethod.GET, params, headers, new TypeReference<MiddlePlatformResult<Map<String, List<MiddlePlatformSubsystem>>>>() {
+            });
+        } catch (SelfException e) {
+            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR, BIZ_TYPE, CLASS_NAME
+                    , String.format("拉取数据失败 error:%s", e)
+            );
+        }
+
+        //获取子系统信息
+        List<MiddlePlatformSubsystem> subsystems = items.getOrDefault(MiddlePlatformMetadata.Results.ROLE_LIST, Collections.emptyList());
+        //递归子系统,获取角色
+        subsystems.forEach(new Consumer<MiddlePlatformSubsystem>() {
+            @Override
+            public void accept(MiddlePlatformSubsystem subsystem) {
+                //填入角色
+                if (subsystem.getRoleList() != null) result.addAll(subsystem.getRoleList());
+                //递归子系统
+                if (subsystem.getChild() != null) subsystem.getChild().forEach(this);
+            }
+        });
+
+        //根据角色id排序去重
+        return new ArrayList<>(result.stream()
+                .sorted(Comparator.comparingLong(role -> Long.parseLong(role.getRoleId()))) // 如果是int类型
+                .collect(Collectors.toMap(
+                        MiddlePlatformRole::getRoleId,
+                        Function.identity(),
+                        (existing, replacement) -> existing,
+                        LinkedHashMap::new
+                )).values());
+    }
+
+
 }

+ 5 - 1
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/constants/MiddlePlatformMetadata.java

@@ -46,7 +46,7 @@ public abstract class MiddlePlatformMetadata extends IntegrationMetadata {
         //获取用户列表
         String GET_USERS = "/PandaCore/GCK/IntegrationAuth/GetUsers";
         //获取用户角色信息
-        String ROLE_GROUP_LIST = "/PandaOMS/OMS/UserCenter/RoleGroupLis";
+        String ROLE_GROUP_LIST = "/PandaOMS/OMS/UserCenter/RoleGroupList";
         //根据Ticket获取用户
         String GET_USER_BY_TICKET = "/PandaOMS/OMS/GetUserByTicket";
     }
@@ -73,6 +73,8 @@ public abstract class MiddlePlatformMetadata extends IntegrationMetadata {
         String PAGE_SIZE = "pageSize";
         //ticket
         String TICKET = "ticket";
+        //用户id
+        String USER_ID = "userID";
     }
 
     /**
@@ -81,6 +83,8 @@ public abstract class MiddlePlatformMetadata extends IntegrationMetadata {
     public interface Results{
         //id
         String ID = "id";
+        //角色列表
+        String ROLE_LIST = "roleList";
     }
 
 

+ 45 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/domain/MiddlePlatformRole.java

@@ -0,0 +1,45 @@
+package com.shkpr.service.customgateway.zydma.domain;
+
+
+import com.fasterxml.jackson.annotation.JsonAlias;
+import com.shkpr.service.customgateway.zydma.domain.po.FunctionInfo;
+import lombok.Data;
+
+/**
+ * 中台角色
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+@Data
+public class MiddlePlatformRole {
+    /**
+     * 角色id
+     */
+    @JsonAlias("roleID")
+    private String roleId;
+
+    private Boolean isChecked;
+    /**
+     * 角色名称
+     */
+    private String roleName;
+
+    private String description;
+
+    private Integer IndexOrder;
+
+    private Integer GroupsOrder;
+
+    private Boolean BuiltInRole;
+
+    private String Comment;
+
+    public FunctionInfo toFunctionInfo() {
+        FunctionInfo functionInfo = new FunctionInfo();
+        functionInfo.setUid(this.roleId);
+        functionInfo.setName(this.roleName);
+        functionInfo.setRemark(this.description);
+        return functionInfo;
+    }
+}

+ 22 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/domain/MiddlePlatformSubsystem.java

@@ -0,0 +1,22 @@
+package com.shkpr.service.customgateway.zydma.domain;
+
+import lombok.Data;
+
+import java.util.List;
+
+/**
+ * 中台子系统
+ */
+@Data
+public class MiddlePlatformSubsystem {
+    private String visibleTitle;
+    private String visibleValue;
+    private String type;
+
+    private List<MiddlePlatformRole> roleList;
+
+    private List<MiddlePlatformSubsystem> child;
+
+    private Integer IndexOrder;
+    private Integer GroupsOrder;
+}

+ 54 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/domain/po/FunctionInfo.java

@@ -0,0 +1,54 @@
+package com.shkpr.service.customgateway.zydma.domain.po;
+
+import lombok.Data;
+
+import java.time.LocalDateTime;
+
+/**
+ * 职能信息表
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+@Data
+public class FunctionInfo {
+    /**
+     * 主键
+     */
+    private Long id;
+
+    /**
+     * 职能唯一ID
+     */
+    private String uid;
+
+    /**
+     * 职能名称
+     */
+    private String name;
+
+    /**
+     * 相关描述
+     */
+    private String remark;
+
+    /**
+     * 预留参数1
+     */
+    private String param1;
+
+    /**
+     * 预留参数2
+     */
+    private String param2;
+
+    /**
+     * 创建时间
+     */
+    private LocalDateTime createTime;
+
+    /**
+     * 修改时间
+     */
+    private LocalDateTime updateTime;
+}

+ 2 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/manager/InfoSyncManager.java

@@ -32,6 +32,7 @@ public class InfoSyncManager {
     public void init() {
         //同步用户信息
         taskScheduler.execute(() -> infoSynchronizer.syncUserInfo(null));
+        taskScheduler.execute(infoSynchronizer::syncFunctionInfo);
     }
 
     /**
@@ -41,5 +42,6 @@ public class InfoSyncManager {
     public void minuteTask() {
         //同步用户信息
         taskScheduler.execute(() -> infoSynchronizer.syncUserInfo(null));
+        taskScheduler.execute(infoSynchronizer::syncFunctionInfo);
     }
 }

+ 21 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/mapper/primary/FunctionInfoMapper.java

@@ -0,0 +1,21 @@
+package com.shkpr.service.customgateway.zydma.mapper.primary;
+
+import com.shkpr.service.customgateway.zydma.domain.po.FunctionInfo;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 用户信息mapper
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+@Mapper
+public interface FunctionInfoMapper {
+    /**
+     * 合并
+     *
+     * @param record 对象
+     * @return 保存数量
+     */
+    int upsert(FunctionInfo record);
+}

+ 22 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/service/FunctionInfoService.java

@@ -0,0 +1,22 @@
+package com.shkpr.service.customgateway.zydma.service;
+
+
+import com.shkpr.service.customgateway.zydma.domain.po.FunctionInfo;
+
+import java.util.List;
+
+/**
+ * 用户信息service
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+public interface FunctionInfoService {
+    /**
+     * 批量合并操作
+     *
+     * @param dates 数据集合
+     * @return 合并状态
+     */
+    Boolean upsertAll(List<FunctionInfo> dates);
+}

+ 101 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/service/impl/FunctionInfoServiceImpl.java

@@ -0,0 +1,101 @@
+package com.shkpr.service.customgateway.zydma.service.impl;
+
+import com.global.base.log.LogLevelFlag;
+import com.global.base.log.LogPrintMgr;
+import com.shkpr.service.customgateway.core.constants.DataSourceNames;
+import com.shkpr.service.customgateway.core.constants.LogFlagBusiType;
+import com.shkpr.service.customgateway.zydma.domain.po.FunctionInfo;
+import com.shkpr.service.customgateway.zydma.mapper.primary.FunctionInfoMapper;
+import com.shkpr.service.customgateway.zydma.service.FunctionInfoService;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.ibatis.session.ExecutorType;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Service;
+
+import java.sql.Connection;
+import java.util.List;
+
+/**
+ * 职能信息service实现
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+@Service
+public class FunctionInfoServiceImpl implements FunctionInfoService {
+    /**
+     * log
+     */
+    private static final String CLASS_NAME = "FunctionInfoServiceImpl";
+    private static final String BIZ_TYPE = LogFlagBusiType.ZAO_YANG_DMA.toStrValue();
+
+    final
+    SqlSessionFactory sqlSessionFactory;
+
+    public FunctionInfoServiceImpl(@Qualifier(DataSourceNames.PRIMARY + "SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
+        this.sqlSessionFactory = sqlSessionFactory;
+    }
+
+    /**
+     * 批量合并操作
+     *
+     * @param dates 数据集合
+     * @return 合并状态
+     */
+    @Override
+    public Boolean upsertAll(List<FunctionInfo> dates) {
+        if (CollectionUtils.isEmpty(dates)) return true;
+
+        LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_INFO, BIZ_TYPE, CLASS_NAME
+                , String.format(
+                        "开始批量写入职能信息,开启批处理 数据量:%s"
+                        , dates.size()
+                )
+        );
+        long begin = System.currentTimeMillis();
+
+        //开启批处理
+        try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
+            try {
+                //设置手动提交
+                Connection conn = sqlSession.getConnection();
+                conn.setAutoCommit(false);
+
+                //从session获取mapper
+                FunctionInfoMapper mapper = sqlSession.getMapper(FunctionInfoMapper.class);
+
+                //批量写入
+                dates.forEach(mapper::upsert);
+
+                //发送sql至数据库
+                sqlSession.flushStatements();
+                //提交
+                sqlSession.commit();
+                conn.commit();
+
+                long end = System.currentTimeMillis();
+                LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_INFO, BIZ_TYPE, CLASS_NAME
+                        , String.format(
+                                "结束批量写入用职能信息,提交并关闭批处理 用时(毫秒):%d"
+                                , (end - begin)
+                        )
+                );
+                return true;
+            } catch (Exception e) {
+                //回滚
+                sqlSession.rollback();
+
+                LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR, BIZ_TYPE, CLASS_NAME
+                        , String.format(
+                                "批量写入职能信息,回滚操作 error:%s"
+                                , e
+                        )
+                );
+
+                return false;
+            }
+        }
+    }
+}

+ 14 - 0
custom-gateway-zydma/src/main/resources/mapper/FunctionInfoMapper.xml

@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.shkpr.service.customgateway.zydma.mapper.primary.FunctionInfoMapper">
+    <insert id="upsert">
+        insert into k4_bs_sys_function_info (uid, "name", remark, update_time)
+        values (#{uid,jdbcType=VARCHAR},
+                #{name,jdbcType=VARCHAR},
+                #{remark,jdbcType=VARCHAR},
+                timezone('utc', localtimestamp(0) at time zone current_setting('timezone')))
+        on conflict (uid) do update set "name"      = excluded."name",
+                                        remark      = excluded.remark,
+                                        update_time = excluded.update_time
+    </insert>
+</mapper>

+ 3 - 0
custom-gateway-zydma/src/main/resources/mapper/PersonnelInfoMapper.xml

@@ -42,6 +42,7 @@
             <if test="phone != null and phone != ''">phone,</if>
             <if test="email != null and email != ''">email,</if>
             <if test="roleId != null and roleId != ''">role_id,</if>
+            <if test="postId != null and roleId != ''">post_id,</if>
             <if test="status != null">status,</if>
             <if test="password != null">"password",</if>
             <if test="org != null and org != ''">org,</if>
@@ -55,6 +56,7 @@
             <if test="phone != null and phone != ''">#{phone,jdbcType=VARCHAR},</if>
             <if test="email != null and email != ''">#{email,jdbcType=VARCHAR},</if>
             <if test="roleId != null and roleId != ''">#{roleId,jdbcType=VARCHAR},</if>
+            <if test="postId != null and postId != ''">#{postId,jdbcType=VARCHAR},</if>
             <if test="status != null">#{status,jdbcType=SMALLINT},</if>
             <if test="password != null">#{password,jdbcType=VARCHAR},</if>
             <if test="org != null and org != ''">#{org,jdbcType=VARCHAR},</if>
@@ -68,6 +70,7 @@
             <if test="realName != null and realName != ''">real_name = #{realName,jdbcType=VARCHAR},</if>
             <if test="phone != null and phone != ''">phone = #{phone,jdbcType=VARCHAR},</if>
             <if test="email != null and email != ''">email = #{email,jdbcType=VARCHAR},</if>
+            <if test="postId != null and postId != ''">post_id = #{postId,jdbcType=VARCHAR},</if>
             <if test="status != null">status = #{status,jdbcType=SMALLINT},</if>
             <if test=" password != null">"password" = #{password,jdbcType=VARCHAR},</if>
             update_time = now()

BIN
data.mv.db