4.2.6 框架之网络请求-拦截器

在整个http的链路中,异常错误对前端来说尤为重要,他作用在很多不同的场景,通用的比如500, 502等; 一个好的软件通常需要在不同的错误场景中做不同的事情。当用户cookie失效时,希望能自动跳转到登录页;当用户权限发生变更时,希望能跳转到一个友好的提示页;那么如何满足这些个性化的诉求呢?接下来让我们一起了解oinone前端网络请求-拦截器。

一、入口

在src目录下main.ts中可以看到VueOioProvider,这是系统功能提供者的注册入口

image.png

图4-2-6-1 VueOioProvider

import interceptor from './middleware/network-interceptor';
VueOioProvider(
  {
    http: {
      callback: interceptor
    }
  },
  []
);

图4-2-6-2 拦截器的申明入口

二、middleware

在项目初始化时使用CLI构建初始化前端工程,在src/middleware有拦截器的默认实现:

image.png

图4-2-6-3 在src/middleware有拦截器的默认实现

三、interceptor

interceptor在请求返回后触发,interceptor有两个回调函数,error和next

error参数

  • graphQLErrors 处理业务异常

  • networkError 处理网络异常

next

  • extensions 后端返回扩展参数
const interceptor: RequestHandler = (operation, forward) => {
  return forward(operation).subscribe({
    error: ({ graphQLErrors, networkError }) => {
            console.log(graphQLErrors, networkError);
      // 默认实现 => interceptor error 
    },
    next: ({ extensions }) => {
            console.log(extensions);
      // 默认实现 => interceptor next 
    },
  });
};

图4-2-6-4 后端返回扩展参数

四、interceptor error

// 定义错误提示等级
const DEFAULT_MESSAGE_LEVEL = ILevel.ERROR;
// 错误提示等级 对应提示的报错
const MESSAGE_LEVEL_MAP = {
  [ILevel.ERROR]: [ILevel.ERROR],
  [ILevel.WARN]: [ILevel.ERROR, ILevel.WARN],
  [ILevel.INFO]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO],
  [ILevel.SUCCESS]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS],
  [ILevel.DEBUG]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS, ILevel.DEBUG]
};
// 错误提示通用函数
const notificationMsg = (type: string = 'error', tip: string = '错误', desc: string = '') => {
  notification[type]({
    message: tip,
    description: desc
  });
};
// 根据错误等级 返回错误提示和类型
const getMsgInfoByLevel = (level: ILevel) => {
  let notificationType = 'info';
  let notificationText = translate('kunlun.common.info');
  switch (level) {
    case ILevel.DEBUG:
      notificationType = 'info';
      notificationText = translate('kunlun.common.debug');
      break;
    case ILevel.INFO:
      notificationType = 'info';
      notificationText = translate('kunlun.common.info');
      break;
    case ILevel.SUCCESS:
      notificationType = 'success';
      notificationText = translate('kunlun.common.success');
      break;
    case ILevel.WARN:
      notificationType = 'warning';
      notificationText = translate('kunlun.common.warning');
      break;
  }
  return {
    notificationType,
    notificationText
  };
};

error: ({ graphQLErrors, networkError }) => {
      if (graphQLErrors) {
        graphQLErrors.forEach(async ({ message, locations, path, extensions }) => {
          let { errorCode, errorMessage, messages } = extensions || {};
          // FIXME: extensions.errorCode
          if (errorCode == null) {
            const codeArr = /code: (\d+),/.exec(message);
            if (codeArr) {
              errorCode = Number(codeArr[1]);
            }
          }
          if (errorMessage == null) {
            const messageArr = /msg: (.*),/.exec(message);
            if (messageArr) {
              errorMessage = messageArr[1];
            }
          }
          // 错误通用提示
          if (messages && messages.length) {
            messages.forEach((m) => {
              notificationMsg('error', translate('kunlun.common.error'), m.message || '');
            });
          } else {
            notificationMsg('error', translate('kunlun.common.error'), errorMessage || message);
          }
            // 提示扩展信息 根据错误等级来提示对应级别的报错
          const extMessage = getValue(response, 'extensions.messages');
          if (extMessage && extMessage.length) {
            const messageLevelArr = MESSAGE_LEVEL_MAP[DEFAULT_MESSAGE_LEVEL];
            extMessage.forEach((m) => {
              if (messageLevelArr.includes(m.level)) {
                const { notificationType, notificationText } = getMsgInfoByLevel(m.level);
                notificationMsg(notificationType, notificationText, m.message || '');
              }
            });
          }

          // 消息模块的用户未登录错误码
          const MAIL_USER_NOT_LOGIN = 20080002;
          // 基础模块的用户未登录错误码
          const BASE_USER_NOT_LOGIN_ERROR = 11500001;
          if (
            [MAIL_USER_NOT_LOGIN, BASE_USER_NOT_LOGIN_ERROR].includes(Number(errorCode)) &&
            location.pathname !== '/auth/login'
          ) {
            const redirect_url = location.pathname;
            location.href = `/login?redirect_url=${redirect_url}`;
          }
          /**
           * 应用配置异常跳转至通用的教程页面
           */
          // 模块参数配置未完成
          const BASE_SYSTEM_CONFIG_IS_NOT_COMPLETED_ERROR = 11500004;
          if ([BASE_SYSTEM_CONFIG_IS_NOT_COMPLETED_ERROR].includes(Number(errorCode))) {
            const action = getValue(response, 'extensions.extra.action');
            if (action) {
              Action.registerAction(action.model, action);
              const searchParams: string[] = [];
              searchParams.push(`module=${action.module}`);
              searchParams.push(`model=${action.model}`);
              searchParams.push(`viewType=${action.viewType}`);
              searchParams.push(`actionId=${action.id}`);
              const href = `${origin}/page;${searchParams.join(';')}`;
              location.href = href;
            }
          }
        });
      }
      if (networkError) {
        const { name, result } = networkError;
        const errMsg = (result && result.message) || `${networkError}`;
        if (name && result && result.message) {
          notification.error({
            message: translate('kunlun.common.error'),
            description: `[${name}]: ${errMsg}`,
          });
        }
      }
    }

图4-2-6-5 interceptor error

四、interceptor next

next: ({ extensions }) => {
  if (extensions) {
    const messages = extensions.messages as {
      level: 'SUCCESS';
      message: string;
    }[];
    if (messages)
      messages.forEach((msg) => {
        notification.success({
          message: '操作成功',
          description: msg.message,
        });
      });
  }
}

图4-2-6-6 interceptor next

六、完整代码

import { NextLink, Operation } from 'apollo-link';
import { notification } from 'ant-design-vue';
import getValue from 'lodash/get';
import { Action, ILevel, translate } from '@kunlun/dependencies';

interface RequestHandler {
  (operation: Operation, forward: NextLink): Promise<any> | any;
}

const DEFAULT_MESSAGE_LEVEL = ILevel.ERROR;
const MESSAGE_LEVEL_MAP = {
  [ILevel.ERROR]: [ILevel.ERROR],
  [ILevel.WARN]: [ILevel.ERROR, ILevel.WARN],
  [ILevel.INFO]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO],
  [ILevel.SUCCESS]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS],
  [ILevel.DEBUG]: [ILevel.ERROR, ILevel.WARN, ILevel.INFO, ILevel.SUCCESS, ILevel.DEBUG]
};

const notificationMsg = (type: string = 'error', tip: string = '错误', desc: string = '') => {
  notification[type]({
    message: tip,
    description: desc
  });
};

const getMsgInfoByLevel = (level: ILevel) => {
  let notificationType = 'info';
  let notificationText = translate('kunlun.common.info');
  switch (level) {
    case ILevel.DEBUG:
      notificationType = 'info';
      notificationText = translate('kunlun.common.debug');
      break;
    case ILevel.INFO:
      notificationType = 'info';
      notificationText = translate('kunlun.common.info');
      break;
    case ILevel.SUCCESS:
      notificationType = 'success';
      notificationText = translate('kunlun.common.success');
      break;
    case ILevel.WARN:
      notificationType = 'warning';
      notificationText = translate('kunlun.common.warning');
      break;
  }
  return {
    notificationType,
    notificationText
  };
};

const interceptor: RequestHandler = (operation, forward) => {
  return forward(operation).subscribe({
    error: ({ graphQLErrors, networkError, response }) => {
      if (graphQLErrors) {
        graphQLErrors.forEach(async ({ message, locations, path, extensions }) => {
          let { errorCode, errorMessage, messages } = extensions || {};
          // FIXME: extensions.errorCode
          if (errorCode == null) {
            const codeArr = /code: (\d+),/.exec(message);
            if (codeArr) {
              errorCode = Number(codeArr[1]);
            }
          }
          if (errorMessage == null) {
            const messageArr = /msg: (.*),/.exec(message);
            if (messageArr) {
              errorMessage = messageArr[1];
            }
          }
          if (messages && messages.length) {
            messages.forEach((m) => {
              notificationMsg('error', translate('kunlun.common.error') || '', m.message || '');
            });
          } else {
            notificationMsg('error', translate('kunlun.common.error') || '', errorMessage || message);
          }

          const extMessage = getValue(response, 'extensions.messages');
          if (extMessage && extMessage.length) {
            const messageLevelArr = MESSAGE_LEVEL_MAP[DEFAULT_MESSAGE_LEVEL];
            extMessage.forEach((m) => {
              if (messageLevelArr.includes(m.level)) {
                const { notificationType, notificationText } = getMsgInfoByLevel(m.level);
                notificationMsg(notificationType, notificationText, m.message || '');
              }
            });
          }
          console.log(extMessage);

          // 消息模块的用户未登录错误码
          const MAIL_USER_NOT_LOGIN = 20080002;
          // 基础模块的用户未登录错误码
          const BASE_USER_NOT_LOGIN_ERROR = 11500001;
          if (
            [MAIL_USER_NOT_LOGIN, BASE_USER_NOT_LOGIN_ERROR].includes(Number(errorCode)) &&
            location.pathname !== '/auth/login'
          ) {
            const redirect_url = location.pathname;
            location.href = `/login?redirect_url=${redirect_url}`;
          }
          /**
           * 应用配置异常跳转至通用的教程页面
           */
          // 模块参数配置未完成
          const BASE_SYSTEM_CONFIG_IS_NOT_COMPLETED_ERROR = 11500004;
          if ([BASE_SYSTEM_CONFIG_IS_NOT_COMPLETED_ERROR].includes(Number(errorCode))) {
            const action = getValue(response, 'extensions.extra.action');
            if (action) {
              Action.registerAction(action.model, action);
              const searchParams: string[] = [];
              searchParams.push(`module=${action.module}`);
              searchParams.push(`model=${action.model}`);
              searchParams.push(`viewType=${action.viewType}`);
              searchParams.push(`actionId=${action.id}`);
              const href = `${origin}/page;${searchParams.join(';')}`;
              location.href = href;
            }
          }
        });
      }
      if (networkError) {
        const { name, result } = networkError;
        const errMsg = (result && result.message) || `${networkError}`;
        if (name && result && result.message) {
          notification.error({
            message: translate('kunlun.common.error') || '',
            description: `[${name}]: ${errMsg}`
          });
        }
      }
    }
  });
};

export default interceptor;

图4-2-6-7 完整代码

Oinone社区 作者:史, 昂原创文章,如若转载,请注明出处:https://doc.oinone.top/oio4/9307.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
史, 昂的头像史, 昂数式管理员
上一篇 2024年5月23日 am8:31
下一篇 2024年5月23日 am8:33

相关推荐

  • 4.1.12 函数之内置函数与表达式

    本文意在列全所有内置函数与表达式,方便大家查阅。 一、内置函数 内置函数是系统预先定义好的函数,并且提供表达式调用支持。 通用函数 数学函数 表达式 名称 说明 ABS 绝对值 函数场景: 表达式函数示例: ABS(number)函数说明: 获取number的绝对值 FLOOR 向下取整 函数场景: 表达式函数示例: FLOOR(number)函数说明: 对number向下取整 CEIL 向上取整 函数场景: 表达式函数示例: CEIL(number)函数说明: 对number向上取整 ROUND 四舍五入 函数场景: 表达式函数示例: ROUND(number)函数说明: 对number四舍五入 MOD 取余 函数场景: 表达式函数示例: MOD(A,B)函数说明: A对B取余 SQRT 平方根 函数场景: 表达式函数示例: SQRT(number) 函数说明: 对number平方根 SIN 正弦 函数场景: 表达式函数示例: SIN(number)函数说明: 对number取正弦 COS 余弦 函数场景: 表达式函数示例: COS(number)函数说明: 对number取余弦 PI 圆周率 函数场景: 表达式函数示例: PI() 函数说明: 圆周率 ADD 相加 函数场景: 表达式函数示例: ADD(A,B)函数说明: A与B相加 SUBTRACT 相减 函数场景: 表达式函数示例: SUBTRACT(A,B)函数说明: A与B相减 MULTIPLY 乘积 函数场景: 表达式函数示例: MULTIPLY(A,B)函数说明: A与B相乘 DIVIDE 相除 函数场景: 表达式函数示例: DIVIDE(A,B)函数说明: A与B相除 MAX 取最大值 函数场景: 表达式函数示例: MAX(collection) 函数说明: 返回集合中的最大值,参数collection为集合或数组 MIN 取最小值 函数场景: 表达式函数示例: MIN(collection) 函数说明: 返回集合中的最小值,参数collection为集合或数组 SUM 求和 函数场景: 表达式函数示例: SUM(collection)函数说明: 返回对集合的求和,参数collection为集合或数组 AVG 取平均值 函数场景: 表达式函数示例: AVG(collection)函数说明: 返回集合的平均值,参数collection为集合或数组 COUNT 计数 函数场景: 表达式函数示例: COUNT(collection)函数说明: 返回集合的总数,参数collection为集合或数组 UPPER_MONEY 大写金额 函数场景: 表达式函数示例: UPPER_MONEY(number)函数说明: 返回金额的大写,参数number为数值或数值类型的字符串 表4-1-12-1 数学函数 文本函数 表达式 名称 说明 TRIM 空字符串过滤 函数场景: 表达式函数示例: TRIM(text)函数说明: 去掉文本字符串text中的首尾空格,文本为空时,返回空字符串 IS_BLANK 是否为空字符串 函数场景: 表达式函数示例: IS_BLANK(text)函数说明: 判断文本字符串text是否为空 STARTS_WITH 是否以指定字符串开始 函数场景: 表达式函数示例: STARTS_WITH(text,start)函数说明: 判断文本字符串text是否以文本字符串start开始,文本为空时,按照空字符串处理 ENDS_WITH 是否以指定字符串结束 函数场景: 表达式函数示例: ENDS_WITH(text,start)函数说明: 判断文本字符串text是否以文本字符串end结束,文本为空时,按照空字符串处理 CONTAINS 包含 函数场景: 表达式函数示例: CONTAINS(text,subtext)函数说明: 判断文本字符串text是否包含文本字符串subtext,文本text为空时,按照空字符串处理 LOWER 小写 函数场景: 表达式函数示例: LOWER(text)函数说明: 小写文本字符串text,文本为空时,按照空字符串处理 UPPER 大写 函数场景: 表达式函数示例: UPPER(text)函数说明: 大写文本字符串text,文本为空时,按照空字符串处理 REPLACE 替换字符串 函数场景: 表达式函数示例: REPLACE(text,oldtext,newtext)函数说明: 使用文本字符串newtext替换文本字符串text中的文本字符串oldtext…

    Oinone 7天入门到精通 2024年5月23日
    1.1K00
  • 3.5.5 设计器的结合(改)

    在页面开发的时候,直接通过前端组件和视图xml进行开发虽然开放性是很大的、但我们经常会忘记视图的配置属性,同时用xml配置的页面因为缺少设计数据,导致无法直接在设计器中复制,自定义页面得从头设计。今天就带大家一起来学习如何结合无代码设计器来完成页面开发,并把设计后的页面元数据装载为标准产品的一部分。 1 安装Docker 如果没有Docker的话,请自行到官网下载:https://www.docker.com/get-started/ 2 下载Docker 镜像,并导入镜像 Step2.1 镜像下载 v.4.6.28.3-allinone-full 版本说明 前后端以及中间件一体 镜像地址 docker pull harbor.oinone.top/oinone/designer:4.6.28.3-allinone-full 下载结构包 oinone-op-ds-all-full.zip(17 KB) v.4.6.28.3-allinone-mini 版本说明 前后端一体支持外部中间件 镜像地址 docker pull harbor.oinone.top/oinone/designer:4.6.28.3-allinone-mini 下载结构包 oinone-op-ds-all-mini.zip(14 KB) v.4.7.9-allinone-full 版本说明 前后端以及中间件一体 镜像地址 docker pull harbor.oinone.top/oinone/designer:4.7.9-allinone-full 下载结构包 oinone-op-ds-all-full.zip(17 KB) v.4.7.9-allinone-mini 版本说明 前后端一体支持外部中间件 镜像地址 docker pull harbor.oinone.top/oinone/designer:4.7.9-allinone-mini 下载结构包 oinone-op-ds-all-mini.zip(14 KB) Step2.1.2 镜像下载用户与密码 需要商业版镜像需要加入Oinone商业版本伙伴专属群,向Oinone技术支持获取用户名与密码,镜像会定时更新并通知大家。 #注意:docker镜像拉取的账号密码请联系数式技术 docker login –username=用户名 harbor.oinone.top docker pull docker pull harbor.oinone.top/oinone/designer:4.6.28.3-allinone-full Step2.1.3 镜像和版本选择 目前有2个版本可供选择,包含中间件以及不包含中间件2个版本,下载结构包以后注意修改startup.sh和startup.cmd中对应镜像地址的版本号。 Step2.1.4 本地结构说明 下载结构包并解压 config是放application.yml的目录,可以在application.yml配置需要启动的自有模块同时修改对应其他中间件配置项 lib是放自有模块的jar包以及其对应的依赖包比如:pamirs-demo-api-1.0.0-SNAPSHOT.jar和pamirs-demo-core-1.0.0-SNAPSHOT.jar nginx:前端运行的nginx站点配置文件 mq:消息配置,再使用低无一体时需要指定mq的broker的IP run:容器运行中间件的脚本,可以对个别中间件是否启动进行设置,(注释掉运行脚本,容器启动时就不会启动该中间件) logs是运行时系统日志目录 Step2.2 修改startup.sh中的路径 Step2.2.1 linux环境修改参数 在文件中找到如下 configDir=/opt/docker/oinone-op-ds-all-full version=4.6.28.3 IP=192.168.0.121 修改configDir的路径(下载oinone-op-ds-xx.zip解压后的路径) 修改对应的镜像版本号 修改对应的IP为docker宿主机IP #!/bin/bash configDir=/opt/docker/oinone-op-ds-all-full version=4.6.28.3 IP=192.168.0.121 docker run -d –name designer-allinone \ -e DUBBO_IP_TO_REGISTRY=$IP \ -e DUBBO_PORT_TO_REGISTRY=20880 \ -p 8099:8091 \ -p 3307:3306 \ -p 2182:2181 \ -p 6378:6379 \ -p 19876:9876 \ -p 10991:10991 \ -p 15555:15555 \ -p 20880:20880 \ -p 88:80 \ -v $configDir/config/:/opt/pamirs/ext \ -v $configDir/nginx:/opt/pamirs/nginx/vhost \ -v $configDir/logs:/opt/pamirs/logs \ -v $configDir/mq/broker.conf:/opt/mq/conf/broker.conf \ -v $configDir/run/run.sh:/opt/pamirs/run/run.sh \ -v $configDir/lib:/opt/pamirs/outlib harbor.oinone.top/oinone/designer:$version-allinone-full Step2.2.3 window环境修改参数 在文件中找到如下 set configDir=/d/shushi/docker/oinone-op-ds-all-full set version=4.6.28.3 set IP=192.168.0.121 修改configDir的路径((下载oinone-op-ds-xx.zip解压后的路径) 修改对应的镜像版本号 修改对应的IP为docker宿主机IP @echo off set configDir=/d/shushi/docker/oinone-op-ds-all-full set version=4.6.28.3 set IP=192.168.0.121 docker run -d –name designer-allinone ^ -e DUBBO_IP_TO_REGISTRY=%IP% ^ -e DUBBO_PORT_TO_REGISTRY=20880 ^ -p 8099:8091…

    2024年5月23日
    1.0K00
  • 企业个性化配置

    平台除了帮助企业快速解决业务需求外,还提供了企业文化、风格个性化能力,本章节详细介绍个性化配置。包括:登陆页配置、企业形象配置、系统风格配置。 系统配置 配置入口 配置入口:右上角登陆账号——系统配置——全局配置——登陆页配置、企业形象配置、系统风格配置。 登陆页配置 用户自定义登陆页的主题,一共有六个主题可选择,分别为: 图一:左侧是图片,右侧是登录输入框,Logo在左上角; 图二:右左侧是图片,右侧是登录输入框,Logo在左上角; 图三:底图是图片,登录输入框浮在页面左侧,Logo在左上角; 图四:底图是图片,登录输入框浮在页面中间,Logo在左上角; 图五:底图是图片,登录输入框浮在页面右侧,Logo在左上角; 图六:底图是图片,登录输入框浮在页面中间,Logo在登录框上方。 页面背景 上传登录页背景,支持上传jpg、png格式的图片或mp4、mov、avi格式视频。尺寸建议为1920*1080px,文件大小不超过50MB。 登录页logo:指配置登录页左上角的logo图标。 预览:配置后可在右侧电脑中点击全屏预览效果。 配置示例 企业形象配置 企业形象配置:可设置企业信息、业务应用导航栏logo、浏览器logo,设置完成之后,点击发布之后设置生效。 系统风格配置 系统风格配置,可设置主题(浅色、深色)、尺寸(大、中、小),配置后可全屏预览,发布后即可更换成对应的风格。 下载代码可进行自定义风格。

    2024年6月20日
    1.0K00
  • 3.1 环境搭建

    一、基础环境说明 内容 是否必须 说明 后端基础环境 JDK1.8 必须 java的基础运行环境, 要求高于1.8_221以上,低于这个版本需要覆盖jce (原因:https://www.cnblogs.com/jinloooong/p/10619353.html) Mysql 必须 8.0.26 版本以上需要注意点:修改:my.cnf (macOS ) / my.ini (windows)时区、大小写敏感设置lower_case_table_names = 2default-time-zone = ‘+08:00’ Idea 必须 需要注意点:1.禁用Lombok插件2.java Compiler 增加 -parameters(不然java反射获取方法入参名会变成arg*) 指令3.安装oinone插件 DB GUI 非必须 Datagrip、MySQLWorkbench、DBEaver 选其一 Insomnia 非必须 GraphQL测试工具 Git 必须 2.2.0以上 Maven 必须 3.6.3需要注意点:1配置mvn的settings文件下载地址见oinone开源社区群公告,也可以联系oinone合作伙伴或服务人员2把settings.xml拷贝一份到maven安装目录conf目录下 RocketMQ 必须 4.7.1以上 Redis 必须 5.0.2以上 Zookeeper 必须 3.5.8以上 前端基础环境 nvm 非必须 方便node的版本管理 nodejs 必须 版本要求为12.12.0注意事项:1.npm的源配置为http://nexus.shushi.pro/repository/kunlun/2.源的用户名、密码见oinone开源社区群公告,也可以联系oinone合作伙伴或服务人员 vue-cli 必须 vue脚手架工具 表3-1-1基础环境说明 其他:canal和Es的环境搭建见具体学习章节 二、基础知识准备 前端必备知识 vue3、typescript、graphql 后端必备知识 SpringBoot、MybatisPlus 表3-1-2基础知识准备 三、下载快速安装包 Mac版 Windows版 四、学习安装 推荐,虽然慢点对环境有比较深入的了解,对自身能力提升和日后排查问题都有好处。 mac见:3.1.1【环境准备(Mac版)】一文 windows见:3.1.2【环境准备(Windows版)】一文

    Oinone 7天入门到精通 2024年5月23日
    2.0K00
  • 6.6 消息

    在我们系统研发过程中经常需要发送短信、邮件、站内信等,笔者在本文给大家介绍下如何使用Oinone的消息模块。 准备工作 如果通过我们工程脚手架工具生成的则已经引入了无需做更多的配置,如果不是则需要按以下步骤先配置依赖和增加启动模块 pamirs-demo-boot的pom文件中引入pamirs-message-core包依赖 <dependency> <groupId>pro.shushi.pamirs.core</groupId> <artifactId>pamirs-message-core</artifactId> </dependency> pamirs-demo-boot的application-dev.yml文件中增加配置pamirs.boot.modules增加message,即在启动应用中增加message模块 pamirs: boot: modules: – message 消息参数设置 发送邮件和短信需要设置对应的发送邮箱服务器和短信云,短信目前默认阿里云短信。我们通过代码示例来完成对应邮箱和短信的参数设置 Step1 增加pamirs-message-api依赖 pamirs-demo-core的pom文件中引入pamirs-message-api包依赖 <dependency> <groupId>pro.shushi.pamirs.core</groupId> <artifactId>pamirs-message-api</artifactId> </dependency> Step2 消息参数设置 请自行替换邮箱服务器和短信通道的账号信息 package pro.shushi.pamirs.demo.core.init; import org.springframework.stereotype.Component; import pro.shushi.pamirs.boot.common.api.command.AppLifecycleCommand; import pro.shushi.pamirs.boot.common.api.init.InstallDataInit; import pro.shushi.pamirs.boot.common.api.init.UpgradeDataInit; import pro.shushi.pamirs.demo.api.DemoModule; import pro.shushi.pamirs.message.enmu.EmailSendSecurityEnum; import pro.shushi.pamirs.message.enmu.MessageEngineTypeEnum; import pro.shushi.pamirs.message.enmu.SMSChannelEnum; import pro.shushi.pamirs.message.model.EmailSenderSource; import pro.shushi.pamirs.message.model.SmsChannelConfig; import java.util.Collections; import java.util.List; @Component public class DemoMessageInit implements InstallDataInit, UpgradeDataInit { private void initEmail(){ EmailSenderSource emailSenderSource = new EmailSenderSource(); emailSenderSource.setName("邮件发送服务"); emailSenderSource.setType(MessageEngineTypeEnum.EMAIL_SEND); //优先级 emailSenderSource.setSequence(10); //发送账号 FIXME 自行替换 emailSenderSource.setSmtpUser(""); //发送密码 FIXME 自行替换 emailSenderSource.setSmtpPassword(""); //发送服务器地址和端口 emailSenderSource.setSmtpHost("smtp.exmail.qq.com"); emailSenderSource.setSmtpPort(465); //" None: SMTP 对话用明文完成。" + //" TLS (STARTTLS): SMTP对话的开始时要求TLS 加密 (建议)" + //" SSL/TLS: SMTP对话通过专用端口用 SSL/TLS 加密 (默认是: 465)") emailSenderSource.setSmtpSecurity(EmailSendSecurityEnum.SSL); emailSenderSource.createOrUpdate(); } private void initSms(){ SmsChannelConfig smsChannelConfig = new SmsChannelConfig(); smsChannelConfig.setType(MessageEngineTypeEnum.SMS_SEND); smsChannelConfig.setChannel(SMSChannelEnum.ALIYUN); //短信签名名称 smsChannelConfig.setSignName("oinone"); //阿里云账号信息 FIXME 自行替换 smsChannelConfig.setAccessKeyId(""); smsChannelConfig.setAccessKeySecret(""); smsChannelConfig.setEndpoint("https://dysmsapi.aliyuncs.com"); smsChannelConfig.setRegionId("cn-hangzhou"); smsChannelConfig.setTimeZone("GMT"); smsChannelConfig.setSignatureMethod("HMAC-SHA1"); smsChannelConfig.setSignatureVersion("1.0"); smsChannelConfig.setVersion("2017-05-25"); smsChannelConfig.createOrUpdate(); //初始化短信模版 //目前支持阿里云短信通道:获取短信模板,如没有短信模板,需要先创建模板,并审核通过 SmsTemplate smsTemplate = new SmsTemplate(); smsTemplate.setName("通知短信"); smsTemplate.setTemplateType(SMSTemplateTypeEnum.NOTIFY); smsTemplate.setTemplateCode("SMS_244595482");//从阿里云获取,自行提供 FIXME smsTemplate.setTemplateContent("尊敬的&{name},你的&{itemName}库存为&{quantity}"); smsTemplate.setChannel(SMSChannelEnum.ALIYUN); smsTemplate.setStatus(SMSTemplateStatusEnum.SUCCESS); smsTemplate.createOrUpdate(); } @Override public boolean init(AppLifecycleCommand command, String version) { initEmail(); initSms(); return Boolean.TRUE; } @Override public boolean upgrade(AppLifecycleCommand command, String version, String existVersion) { initEmail(); initSms(); return Boolean.TRUE; } @Override public List<String> modules() { return Collections.singletonList(DemoModule.MODULE_MODULE);…

    2024年5月23日
    1.1K00

Leave a Reply

登录后才能评论