<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0"><channel><title>Takagi</title><link>https://lixingyong.com/</link><atom:link href="https://lixingyong.com/rss.xml" rel="self" type="application/rss+xml"/><description> You got to put the past behind you before you can move on. </description><generator>Halo v2.26.0</generator><language>zh-cn</language><image><url>https://cdn.lixingyong.com/halo-sakura/image/site-logo.png?image_process=resize,w_160</url><title>Takagi</title><link>https://lixingyong.com/</link></image><lastBuildDate>Tue, 10 Nov 2026 08:36:35 GMT</lastBuildDate><item><title><![CDATA[Halo 主题 PJAX 开发实践]]></title><link>https://lixingyong.com/archives/halo-zhu-ti-pjax-zui-jia-shi-jian</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=Halo%20%E4%B8%BB%E9%A2%98%20PJAX%20%E5%BC%80%E5%8F%91%E5%AE%9E%E8%B7%B5&amp;url=/archives/halo-zhu-ti-pjax-zui-jia-shi-jian" width="1" height="1" alt="" style="opacity:0;">
<p style="text-indent: 2em">在 Web 开发过程中，如何实现局部页面加载一直是一个热门话题。以单页面应用（SPA）为例，它通过路由机制实现局部页面加载，是一种常见的前端解决方案。而对于内容管理系统（CMS），其通常采用传统的服务端渲染（SSR）模式，如果不使用额外的技术优化，CMS 往往是多页面应用（MPA），即每次页面请求都会加载完整的 JS 和 CSS 资源。</p>
<p style="text-indent: 2em">PJAX（PushState + AJAX）可以看作是多页面应用与单页面应用之间的过渡技术。在保留原有服务端渲染和页面结构的基础上，它通过局部更新页面内容，提升用户体验。此外，由于页面结构得以保留，PJAX 也不会带来单页面应用常见的 SEO 问题。</p>
<p style="text-indent: 2em">PJAX 适用于某些特定场景，比如网站拥有全局媒体播放器时，PJAX 能在页面切换时保持播放不中断；又如需要异步加载页面内容、提升用户体验时，它也能发挥作用。然而，PJAX 同样存在一些缺点，如增加开发和维护的复杂性，尤其是在全局状态管理和路由处理方面。因此，尽管本篇文章重点介绍 PJAX 技术，但如果项目中没有强烈需求，也并不推荐使用 PJAX，需综合权衡它所带来的便利与额外成本。</p>
<p style="text-indent: 2em">需要补充的是，用于服务端渲染的多页面应用的局部加载技术有很多，PJAX 只是其中一种。而随着前端技术的快速迭代，PJAX 已经逐渐不再具有竞争力。本文的结尾会介绍其他的相关技术用于参考。</p>
<p style="text-indent: 2em">接下来，我将基于实际的 Halo 主题开发，介绍 PJAX 的具体实践。</p>
<h2 style="" id="pjax-%E7%9B%B8%E5%85%B3%E5%BA%93">PJAX 相关库</h2>
<p style="text-indent: 2em">在实际开发中，我们通常会借助现有的库来提高开发效率。PJAX 的相关库通常封装了浏览器的 PushState 和 AJAX 请求逻辑，能够大幅减少手动实现的工作量。</p>
<ul>
 <li>
  <p style=""><hyperlink-inline-card target="_blank" href="https://github.com/defunkt/jquery-pjax" theme="inline" custom-title="defunkt/jquery-pjax"><a href="https://github.com/defunkt/jquery-pjax" target="_blank">https://github.com/defunkt/jquery-pjax</a></hyperlink-inline-card></p>
 </li>
</ul>
<p style="">这是一个基于 JQuery 的插件，通过 PushState 和 AJAX 实现 PJAX。虽然功能齐全，但它依赖于 JQuery，且最后一个版本发布于 2017 年，已经长期未维护。</p>
<ul>
 <li>
  <p style=""><hyperlink-inline-card target="_blank" href="https://github.com/MoOx/pjax" theme="inline" custom-title="MoOx/pjax"><a href="https://github.com/MoOx/pjax" target="_blank">https://github.com/MoOx/pjax</a></hyperlink-inline-card></p>
 </li>
</ul>
<p style="">该库完全使用原生 JavaScript 实现，通过 PushState 和 XHR 完成 PJAX 的功能。最后一次发布版本是在 2019 年，同样处于未维护状态。</p>
<p style="text-indent: 2em">从这些库可以看出，PJAX 作为一种过渡技术，其相关库已经颇具年代感，然而，这并不妨碍它在特定场景中的使用。个人推荐使用 <code>MoOx/pjax</code>，因为它脱离了对 JQuery 的依赖，能够与各种框架集成。</p>
<h2 style="" id="halo-%E4%B8%BB%E9%A2%98%E5%BC%80%E5%8F%91%E8%9E%8D%E5%90%88-pjax">Halo 主题开发融合 PJAX</h2>
<p style="text-indent: 2em">本文将以我开发的 <a href="https://github.com/LIlGG/halo-theme-sakura">Halo 主题 Sakura</a> 为例，详细讲解 PJAX 在 Halo 主题开发中的应用。我将分享我如何在主题中实现 PJAX、为什么选择使用它、遇到的问题及相应的解决方案。</p>
<h3 style="" id="%E4%B8%BA%E4%BB%80%E4%B9%88%E9%80%89%E6%8B%A9%E4%BD%BF%E7%94%A8-pjax">为什么选择使用 PJAX</h3>
<p style="text-indent: 2em">在我的主题中，有全局的媒体播放器功能，并集成了诸如 <a href="https://github.com/LIlGG/plugin-live2d">Plugin-Live2d</a> 这样的插件。我希望在用户浏览不同页面时，媒体播放和看板娘等全局元素不会被刷新。同时，我希望能够通过异步懒加载来优化资源的加载——在首页仅加载部分必要资源，而剩余资源将在用户点击其他页面时动态加载，从而提高首屏的加载速度。基于这些需求，我最终选择在主题中引入 PJAX 进行优化。</p>
<h3 style="" id="%E4%B8%BB%E9%A2%98%E4%B8%AD%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8-pjax">主题中如何使用 PJAX</h3>
<p style="text-indent: 2em">在主题中集成 PJAX 相对简单，只需要通过 <code>&lt;script&gt;</code> 标签将 PJAX 加载到网页中即可。如果使用构建工具，可以将打包后的文件（如 <code>pjax.min.js</code>）链接到页面，具体步骤可参考 <a href="https://github.com/MoOx/pjax#installation" target="_new" rel="noopener">MoOx/pjax 的安装说明</a>。</p>
<p style="text-indent: 2em">然而，PJAX 的默认配置往往无法满足实际开发需求。以我的主题为例，以下是我在主题中使用 PJAX 的基本配置：</p>
<pre><code class="language-typescript">const pjax = new Pjax({
  elements: "a[data-pjax]", // 触发 PJAX 的条件，当点击具有 data-pjax 属性的 &lt;a&gt; 标签时触发 PJAX。
  selectors: ["head title", ".wrapper", ".pjax"], // 定义需要替换的页面区域。
  switches: {
    ".wrapper": Pjax.switches.innerHTML,
  }, // 定义旧元素如何替换为新元素。
  analytics: false, // 关闭自动调用页面分析，建议通过其他方式处理。
  cacheBust: false, // 关闭跳过浏览器缓存
  debug: import.meta.env.MODE === "development" ? true : false, // 在开发模式下启用调试信息。
});</code></pre>
<p style="text-indent: 2em">在这个配置中，最关键的两个参数是 <code>elements</code> 和 <code>selectors</code>：</p>
<ul>
 <li>
  <p style=""><strong>elements</strong> 指定了哪些元素会触发 PJAX，例如带有 <code>data-pjax</code> 属性的 <code>&lt;a&gt;</code> 标签；</p>
 </li>
 <li>
  <p style=""><strong>selectors</strong> 定义了页面中哪些区域会在 PJAX 加载时被替换。</p>
 </li>
</ul>
<p style=""><code>switches</code> 参数则用于定义页面元素如何进行替换，比如 <code>Pjax.switches.innerHTML</code> 使用<code>`innerHTML</code> 及原有元素上的 class 。</p>
<p style="text-indent: 2em">按此配置，理论上网站已经可以正常使用 PJAX。然而在实际开发中，仍然会遇到很多问题，主要集中在脚本的执行上。PJAX 不会自动重新加载非替换区域的脚本，而对于替换区域的脚本，它仅会简单的执行一次。因此这就带来了一系列问题，包括但不限于：</p>
<ol>
 <li>
  <p style=""><strong>脚本支持问题</strong>：新替换的内容可能依赖已经加载的脚本，因此需要重新加载相关脚本；</p>
 </li>
 <li>
  <p style=""><strong>脚本方法需要重新执行</strong>：新内容可能依赖已加载脚本的某些方法，但无需重新加载整个脚本，只需重新执行特定方法；</p>
 </li>
 <li>
  <p style=""><strong>DOMContentLoaded 事件问题</strong>：某些脚本依赖于浏览器的 <code>DOMContentLoaded</code> 事件，这在 PJAX 环境下不会再次触发；</p>
 </li>
 <li>
  <p style=""><strong>第三方脚本问题</strong>：需要重新加载的脚本可能位于非替换区，或加载方式不公开（例如第三方脚本）；</p>
 </li>
 <li>
  <p style=""><strong>PJAX 无法包含新内容</strong>：一些未通过 PJAX 加载的内容，加载完成后无法被 PJAX 管理。</p>
 </li>
</ol>
<h3 style="" id="%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88">问题解决方案</h3>
<p style="">以下是我在 Sakura 主题中应对上述问题的解决方案。虽然这些方案并不一定完美，但希望能为有类似需求的开发者提供参考。</p>
<p style=""><strong>问题 1：新替换的内容需要重新加载已加载的脚本</strong></p>
<p style="text-indent: 2em">这是最常见的问题之一，尤其当某些脚本需要在每个页面执行，而不依赖于特定页面数据时，例如页面分析代码。</p>
<p style="text-indent: 2em">解决方案通常是在 PJAX 替换内容成功后，重新执行已加载的脚本。常见的处理方式是移除旧的 <code>&lt;script&gt;</code> 标签并将其重新添加到 DOM 中。代码示例如下：</p>
<pre><code class="language-typescript">window.addEventListener("pjax:success", () =&gt; {
  // 对具有 data-pjax 属性的脚本进行重新加载
  let pjaxDoms = document.querySelectorAll("script[data-pjax]") as NodeListOf&lt;HTMLScriptElement&gt;;
  pjaxDoms.forEach((element) =&gt; {
    let code: string = element.text || element.textContent || element.innerHTML || "";
    let parent: ParentNode | null = element.parentNode;
    if (parent === null) {
      return;
    }
    // 移除旧的 script 标签
    parent.removeChild(element);
    // 创建新的 script 标签并重新添加到 DOM 中
    let script: HTMLElementTagNameMap["script"] = document.createElement("script");
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = "";
    }
    if (code !== "") {
      // 插入原始的脚本内容
      script.appendChild(document.createTextNode(code));
    }
    // 将新 script 插入到文档中
    parent.appendChild(script);
  });
});</code></pre>
<p style="text-indent: 2em">通过上述方式，确保了在 PJAX 加载新页面后，相关脚本能够重新执行。建议为所有需要支持 PJAX 的脚本都添加 <code>data-pjax</code> 属性，以便统一管理和重新加载。</p>
<p style=""><strong>问题 2：新替换的内容需要已加载脚本的部分方法支持，但不重新加载脚本，仅重新执行方法</strong></p>
<p style="text-indent: 2em">这种情况同样常见，例如 Halo 旧版本的评论组件会在首页进行加载，但评论功能实际用于各个内容页面，且依赖新页面的数据。为了处理此类需求，本主题实现了一个全局状态管理机制，专门处理此类场景。</p>
<p style="text-indent: 2em">首先，当页面通过 PJAX 加载完成后，触发状态刷新事件：</p>
<pre><code class="language-typescript">window.addEventListener("pjax:success", () =&gt; {
  // 调用 sakura 的 refresh 方法，重新执行需要的方法或功能
  sakura.refresh();
});</code></pre>
<p style="text-indent: 2em"><code>refresh</code> 方法用于重新调用目标脚本中的功能，而无需重新加载整个脚本。比如，以下代码重新执行评论组件的初始化：</p>
<pre><code class="language-typescript">const registerCommentWidget = (id: string, group: string, kind: string, name: string): Promise&lt;string&gt; =&gt; {
  return new Promise((resolve, reject) =&gt; {
    if (!CommentWidget) {
      return reject("Failed to fetch data");
    }
    // 初始化评论组件
    CommentWidget.init(
      `#${id}`,
      "/plugins/PluginCommentWidget/assets/static/style.css",
      {
        group: group,
        kind: kind,
        name: name,
        colorScheme: 'light'
      }
    );
    resolve("success");
  });
};</code></pre>
<p style="text-indent: 2em">在这个实现中，<code>registerCommentWidget</code> 方法不会重新加载 <code>CommentWidget</code>，而是直接调用它的初始化方法来支持新页面的数据。这样可以避免不必要的脚本重复加载，提升页面性能。</p>
<blockquote>
 <p style="">注：上述代码为旧版代码，仅用于说明问题解决方案。</p>
</blockquote>
<p style=""><strong>问题 3：替换区域的脚本依赖于浏览器的 </strong><code>DOMContentLoaded</code><strong> 事件</strong></p>
<p style="text-indent: 2em">如果脚本依赖于 <code>DOMContentLoaded</code> 事件来执行，当页面通过 PJAX 刷新时，这些脚本将无法正常运行，因为 PJAX 并不会重新触发浏览器的 <code>DOMContentLoaded</code> 事件。即使我们通过移除并重新添加脚本的方式来处理，这类脚本也无法执行，因为它们始终依赖浏览器的 <code>DOMContentLoaded</code>，而该事件只会在页面初次完全加载时触发一次。</p>
<p style="text-indent: 2em">为了解决这个问题，本主题使用了<strong>事件代理</strong>的方式，将所有监听 <code>DOMContentLoaded</code> 事件的脚本转化为监听 <code>pjax:success</code> 事件，从而保证相关方法在 PJAX 完成后能够正确执行。实现如下：</p>
<pre><code class="language-typescript">const originalAddEventListener = EventTarget.prototype.addEventListener;

EventTarget.prototype.addEventListener = function (type, listener, options) {
  // 检查是否是 'DOMContentLoaded' 事件类型
  if (type === "DOMContentLoaded") {
    if (listener) {
      window.addEventListener(
        "pjax:success",
        () =&gt; {
          // 使用自定义的重试机制执行 DOMContentLoaded 的逻辑
          Util.retry(() =&gt; listener(), 10, 100);
        },
        {
          once: true,  // 确保只执行一次
        }
      );
      return;
    }
  }
  // 对于其他事件类型，调用原始的 addEventListener 方法
  originalAddEventListener.call(this, type, listener, options);
};</code></pre>
<p style="text-indent: 2em">这段代码通过代理 <code>addEventListener</code> 方法，拦截所有对 <code>DOMContentLoaded</code> 的事件绑定操作，将其转换为对 <code>pjax:success</code> 事件的监听。具体做法是，每当有脚本试图绑定 <code>DOMContentLoaded</code> 事件时，我会将其改为监听 <code>pjax:success</code> 事件，并使用自定义的 <code>retry</code> 方法确保回调函数能够执行。这种方法可以保证即使在 PJAX 环境下，依赖 <code>DOMContentLoaded</code> 事件的脚本仍能被触发。</p>
<p style="text-indent: 2em">通过这种方式，脚本不再依赖于页面初次加载时的 <code>DOMContentLoaded</code> 事件，而是在 PJAX 页面切换时依然能正常执行其逻辑。</p>
<p style=""><strong>问题 4：需要重新加载的脚本位于非加载区，或其加载方法不公开（通常为第三方脚本）</strong></p>
<p style="text-indent: 2em">这类问题是 PJAX 应用中最棘手的问题，尤其在涉及第三方脚本时。以 Halo 为例，文章页面会通过 <code>script</code> 增加访问量统计，但首页并不包含该脚本。这意味着如果用户从首页访问文章页，统计脚本不会加载，导致访问量无法统计。如果用户在文章页内切换其他文章，统计脚本也不会为新文章记录访问量，因为该脚本依赖于特定页面的数据，处理起来更加复杂。</p>
<p style="">解决这类问题的方案有限，以下是常见的几种处理方式：</p>
<ul>
 <li>
  <p style=""><strong>服务端渲染动态添加脚本</strong></p>
  <ul>
   <li>
    <p style="">由脚本提供方确保在每个页面都包含相关脚本，或将脚本移动到 PJAX 的加载区域。这样脚本将能够在页面切换时始终保持可用状态。</p>
   </li>
  </ul>
 </li>
 <li>
  <p style=""><strong>公开脚本方法</strong></p>
  <ul>
   <li>
    <p style="">如果第三方脚本能够抛出公开的方法，PJAX 可以通过调用此方法来初始化或重新加载该脚本。例如，脚本提供方可以提供一个函数接口，允许开发者在 PJAX 切换页面时主动调用该方法。</p>
   </li>
  </ul>
 </li>
 <li>
  <p style=""><strong>监听 PJAX 事件</strong></p>
  <ul>
   <li>
    <p style="">如果第三方脚本能够监听 <code>pjax:success</code> 或 <code>DOMContentLoaded</code> 事件，可以在这些事件触发时重新初始化脚本。这种方式能够确保脚本在 PJAX 页面切换后依然能够正确运行。</p>
   </li>
  </ul>
 </li>
 <li>
  <p style=""><strong>主题中特殊处理</strong></p>
  <ul>
   <li>
    <p style="">在主题中进行定制处理，例如为 <code>selectors</code> 添加对该脚本的特殊识别，确保在 PJAX 替换时能够识别并处理该脚本。然后通过 <code>switches</code> 对脚本进行替换，保证新页面中该脚本能够重新加载和执行。</p>
   </li>
  </ul>
 </li>
</ul>
<p style=""><strong>问题 5：由非 PJAX 加载的内容，加载完成后无法享受到 PJAX</strong></p>
<p style="text-indent: 2em">这种问题通常出现在分页加载的场景中。当新加载分页内容的请求没有使用 PJAX 时，新内容自然也就无法享受 PJAX 的功能。为了解决这一问题，我们需要在动态加载内容后重新注册 PJAX 功能，确保新加载的内容能够继续参与 PJAX 的交互。</p>
<pre><code class="language-typescript">  public registerPostListPaginationEvent() {
    const paginationElement = document.getElementById("pagination");
    if (!paginationElement) {
      return;
    }
    const listPaginationLinkElement = paginationElement.querySelector("a");
    if (!listPaginationLinkElement) {
      return;
    }
    listPaginationLinkElement.addEventListener("click", (event) =&gt; {
      event.preventDefault();
      const postListElement = document.getElementById("main");
      if (!postListElement) {
        return;
      }
      const targetElement = event.target as HTMLLinkElement;
      const url = targetElement.href;
      targetElement.classList.add("loading");
      targetElement.textContent = "";
      fetch(url, {
        method: "GET",
      })
        .then((response) =&gt; response.text())
        .then((html) =&gt; {
          const parser = new DOMParser();
          const doc = parser.parseFromString(html, "text/html");
          const postListNewElements = doc.querySelectorAll("#main .post");

          // 将新文章追加到文章列表
          if (postListNewElements &amp;&amp; postListNewElements.length &gt; 0) {
            postListNewElements.forEach((element) =&gt; {
              postListElement.appendChild(element);
            });
          }

          // 绑定新的 DOM 元素至 PJAX 上，确保新内容享受到 PJAX
          if (sakura.$pjax) {
            sakura.$pjax.refresh(postListElement);
          }
          
          // 更新分页链接
          const nextPaginationElement = doc.querySelector("#pagination a") as HTMLLinkElement;
          if (nextPaginationElement) {
            targetElement.href = nextPaginationElement.href;
          } else {
            paginationElement.innerHTML = `&lt;span&gt;${sakura.translate("page.theend", "没有更多文章了")}&lt;/span&gt;`;
          }
        })
        .catch((error) =&gt; {
          console.error(error);
        })
        .finally(() =&gt; {
          targetElement.classList.remove("loading");
          targetElement.textContent = sakura.translate("page.next", "下一页");
        });
      return false;
    });
  }</code></pre>
<p style="text-indent: 2em">在分页数据加载完成后，调用 <code>pjax.refresh(postListElement)</code> 重新注册 PJAX 功能，确保新加载的文章列表能够享受 PJAX 的页面切换功能。</p>
<h3 style="" id="halo-%E4%B8%AD%E7%9A%84%E7%89%B9%E6%AE%8A%E9%97%AE%E9%A2%98">Halo 中的特殊问题</h3>
<p style="text-indent: 2em">在 Halo 中，PJAX 请求还会引发一些特定问题。例如，在发送 PJAX 请求时，默认的请求头只包含 <code>accept: *</code>，<em> </em>这导致 Halo 无法拦截请求以获取 <code>Security Context</code> 。</p>
<p style="text-indent: 2em">为了避免这种问题，我们需要手动设置正确的 <code>Accept</code> 头信息，使得 Halo 可以正确处理这些请求。在 PJAX 请求中，可以将 <code>Accept</code> 头设置为 <code>text/html, application/json, text/plain, */*</code> ，用于处理此问题。此解决方案的详细代码可以参考 <a href="https://github.com/LIlGG/halo-theme-sakura/pull/476">PR<span style="font-size: var(--h1-size, 32)px; color: var(--fgColor-muted, var(--color-fg-muted))">#476</span></a><span style="font-size: var(--h1-size, 32)px; color: var(--fgColor-muted, var(--color-fg-muted))">。</span></p>
<h2 style="" id="pjax-%E5%AE%9E%E8%B7%B5%E7%BB%8F%E9%AA%8C">PJAX 实践经验</h2>
<p style="text-indent: 2em">在开发过程中，使用 PJAX 来优化主题的局部页面加载，确实能够提升用户体验，但与此同时，它也带来了不小的开发和维护成本，甚至可能会遇到难以解决的技术障碍。基于我的个人实践，以下是一些使用 PJAX 的经验总结：</p>
<ol>
 <li>
  <p style=""><strong>优先选择替代方案</strong>
   <br>
   如果仅仅是为了提升用户体验，不要轻易使用 PJAX。在许多情况下，其他优化手段（如延迟加载、按需加载等）可能更为高效，且更容易实现，避免了 PJAX 带来的复杂性。</p>
 </li>
 <li>
  <p style=""><strong>避免在 </strong><code>head</code><strong> 标签中添加非全局脚本</strong>
   <br>
   PJAX 通常不会替换整个 <code>head</code> 区域，而只替换特定的内容。因此，如果在 <code>head</code> 标签中添加了某些仅在部分页面使用的脚本，PJAX 可能无法正常加载这些脚本。尽量将页面中可选的或动态的脚本放置在可替换的区域内，而不是 <code>head</code> 标签中。</p>
 </li>
 <li>
  <p style=""><strong>明确配置 </strong><code>elements</code><strong> 属性</strong>
   <br>
   一定要明确配置 PJAX 中的 <code>elements</code> 选项。默认情况下，PJAX 会将所有的 <code>&lt;a&gt;</code> 标签都设为可触发 PJAX 请求，但这样可能会导致某些意料之外的问题，例如错误的链接被 PJAX 处理。通过精确指定触发 PJAX 的链接（如 <code>[a[data-pjax]]</code>），可以避免这种情况，提高系统的稳定性。</p>
 </li>
 <li>
  <p style=""><strong>遵循约定大于配置</strong>
   <br>
   在 Halo 中，部分脚本可能已支持 PJAX 刷新，但通常会使用约定俗成的方法。如果某个脚本需要在页面局部刷新后重新执行，建议为该脚本添加如 <code>class="pjax"</code> 的标记。这样可以确保这些脚本在 PJAX 刷新后得到正确处理。因此，建议在主题 PJAX的 <code>elements</code> 属性中增加 <code>.pjax</code> 选择器，以便正确处理需要局部刷新的脚本。</p>
 </li>
</ol>
<h2 style="" id="%E7%9B%B8%E5%85%B3%E6%8A%80%E6%9C%AF">相关技术</h2>
<p style="text-indent: 2em">实际上，实现多页面应用局部加载的技术有很多，其中大多数比 PJAX 更加现代化和通用。因此，如果有这类需求，建议在进行充分调研后选择适合的技术方案。下面是几种常见的、与 PJAX 相近的技术，它们在不同场景下具有各自的优势和特点。</p>
<ol>
 <li>
  <p style=""><a href="https://github.com/hotwired/turbo" target="_new" rel="noopener"><strong>Turbo</strong></a>
   <br>
   Turbo 是 GitHub 使用的一种局部页面加载技术，与 PJAX 相比，它更加重量级，但也封装了更多功能，能够简化客户端的开发。作为 Hotwire 前端框架的一部分，Turbo 尤其适合基于 Rails 架构的应用程序。它在处理表单、响应性页面更新等方面表现出色，并且支持无刷新加载和缓存，提升了开发效率。</p>
 </li>
 <li>
  <p style=""><a href="https://github.com/bigskysoftware/htmx" target="_new" rel="noopener"><strong>htmx</strong></a>
   <br>
   htmx 和 PJAX 一样能够实现页面的局部更新，但两者的实现方式和关注点有所不同。htmx 强调通过 HTML 属性控制动态表单、实时数据更新、WebSocket 集成等功能，使其在构建交互式和响应式的网页时更为灵活，是一个更广泛适用的选择。</p>
 </li>
 <li>
  <p style=""><a href="https://github.com/barbajs/barba" target="_new" rel="noopener"><strong>barba.js</strong></a>
   <br>
   barba.js 以创建平滑的页面过渡效果为核心，能够在页面切换时提供更佳的用户体验。如果你的应用对动画效果和视觉体验有较高要求，barba.js 是一个很好的选择，尤其是在构建具有复杂转场动画的网站时非常有用。</p>
 </li>
 <li>
  <p style=""><a href="https://github.com/unpoly/unpoly" target="_new" rel="noopener"><strong>Unpoly</strong></a>
   <br>
   Unpoly 是一个比 PJAX 更现代化的解决方案，不仅能够实现局部页面更新，还增加了转场动画、缓存和模态框等功能支持。它的 API 更加通用和友好，能够在不引入太多复杂性的情况下，提供全面的局部加载功能，是比 PJAX 更值得考虑的选择之一。</p>
 </li>
</ol>
<p style=""></p>]]></description><guid isPermaLink="false">/archives/halo-zhu-ti-pjax-zui-jia-shi-jian</guid><dc:creator>Takagi</dc:creator><category>Halo 主题开发</category><category>Halo 插件开发</category><category>Halo</category><pubDate>Mon, 26 Aug 2024 02:23:35 GMT</pubDate></item><item><title><![CDATA[Halo 搜索文档扩展]]></title><link>https://lixingyong.com/archives/halo-cha-jian-kuo-zhan-sou-suo-yin-qing</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=Halo%20%E6%90%9C%E7%B4%A2%E6%96%87%E6%A1%A3%E6%89%A9%E5%B1%95&amp;url=/archives/halo-cha-jian-kuo-zhan-sou-suo-yin-qing" width="1" height="1" alt="" style="opacity:0;">
<h2 style="" id="%E5%89%8D%E8%A8%80">前言</h2>
<p style="">Halo 搜索引擎在 <a href="https://github.com/halo-dev/halo/releases/tag/v2.17.0">https://github.com/halo-dev/halo/releases/tag/v2.17.0</a> 版本后进行了重大重构，详见 <a href="https://github.com/halo-dev/halo/pull/6082">https://github.com/halo-dev/halo/pull/6082</a>。因此，在 Halo 2.17 版本之后，插件作者可以通过插件对 Halo 搜索进行扩展。</p>
<p style="">对 Halo 搜索的扩展可以分为两个部分：搜索引擎扩展和搜索文档扩展。</p>
<h3 style="" id="%E6%90%9C%E7%B4%A2%E5%BC%95%E6%93%8E%E6%89%A9%E5%B1%95">搜索引擎扩展</h3>
<p style="">在插件中，可以通过扩展搜索引擎来提供更为丰富的搜索功能。例如，Halo 默认使用的是 <code>Lucene</code> ，但插件可以通过扩展支持其他搜索引擎，如 <code>Solr</code> 、 <code>MeiliSearch</code> 、 <code>ElaticSearch</code> 。</p>
<p style="">不过，搜索引擎扩展不在本文讨论范围内，有兴趣的小伙伴可以阅读<a href="https://github.com/halo-dev/halo/blob/main/docs/extension-points/search-engine.md"> Halo 搜索引擎扩展点</a> 以了解更多详情。</p>
<h3 style="" id="%E6%90%9C%E7%B4%A2%E6%96%87%E6%A1%A3%E6%89%A9%E5%B1%95">搜索文档扩展</h3>
<p style="">如果你的插件提供了新的内容数据，例如 <code>Moment</code> ，使用搜索功能时，你会发现无法搜到 <code>Moment</code> 中的任何内容。这是因为 Halo 默认只提供了文章与页面这两种核心内容的搜索。</p>
<p style="">对于自建的内容数据，Halo 搜索不会自动补充，因为自定义数据结构可能与文章和页面截然不同。因此，插件作者就需要主动将自己的内容数据提交至 Halo 搜索。</p>
<p style="">接下来，我将基于 <a href="https://github.com/halo-sigs/plugin-moments">Halo Moment 插件</a> 这个实际案例，详细介绍如何扩展搜索文档。</p>
<h2 style="" id="%E6%90%9C%E7%B4%A2%E6%96%87%E6%A1%A3%E4%BA%8B%E4%BB%B6">搜索文档事件</h2>
<p style="">Halo 搜索利用事件机制来收集核心和插件中发布的文档。当插件发布某个文档事件后，Halo 搜索会添加、更新、删除与重建目标文档索引。</p>
<p style="">要将插件的内容数据提供给搜索，最佳做法是插件主动发出特定事件供 Halo 消费。</p>
<p style="">目前（Halo 版本 2.17.1）， Halo 搜索共监听了三个事件：</p>
<ul>
 <li>
  <p style="">添加文档事件 - <code>HaloDocumentAddRequestEvent</code></p>
 </li>
 <li>
  <p style="">删除文档事件 - <code>HaloDocumentDeleteRequestEvent</code></p>
 </li>
 <li>
  <p style="">重建索引事件 - <code>HaloDocumentRebuildRequestEvent</code></p>
 </li>
</ul>
<h3 style="" id="halodocumentaddrequestevent">HaloDocumentAddRequestEvent</h3>
<p style="">用于添加或更新文档，例如在 Moment 中添加或更新文档的示例如下：</p>
<pre><code class="language-java">// MomentReconciler.java
// Create moment search document
var haloDoc = converter.convert(moment).blockOptional().orElseThrow();
eventPublisher.publishEvent(new HaloDocumentAddRequestEvent(this, List.of(haloDoc)));</code></pre>
<h3 style="" id="halodocumentdeleterequestevent">HaloDocumentDeleteRequestEvent</h3>
<p style="">用于从搜索索引中删除文档，例如删除 Moment 搜索索引的示例如下：</p>
<pre><code class="language-java">// MomentReconciler.java
eventPublisher.publishEvent(new HaloDocumentDeleteRequestEvent(this,
  // Get moment search document id
  List.of(converter.haloDocId(moment)))
);</code></pre>
<h3 style="" id="halodocumentrebuildrequestevent">HaloDocumentRebuildRequestEvent</h3>
<p style="">用于重新获取搜索文档索引，示例如下：</p>
<pre><code class="language-java">eventPublisher.publishEvent(new HaloDocumentRebuildRequestEvent(this));</code></pre>
<h2 style="" id="%E5%AE%9E%E7%8E%B0%E6%96%87%E6%A1%A3%E6%89%A9%E5%B1%95">实现文档扩展</h2>
<p style="">除了使用搜索文档事件添加、更新、删除某个特定文档之外，插件还需要实现 <code>HaloDocumentsProvider</code> 接口，该接口用于重建搜索索引。</p>
<h2 style="" id="%E6%A1%88%E4%BE%8B---moment-%E6%8F%92%E4%BB%B6%E6%90%9C%E7%B4%A2%E6%96%87%E6%A1%A3%E5%90%8C%E6%AD%A5">案例 - Moment 插件搜索文档同步</h2>
<p style="">了解 Halo 搜索文档同步事件之后，便可以进行文档同步了。以下是 Moment 插件搜索文档同步的步骤：</p>
<ol>
 <li>
  <p style="">创建一个 <code>Reconciler</code> 用于处理 Moment 内容更新后的搜索相关业务：</p>
 </li>
</ol>
<pre collapsed="true"><code class="language-java">@Component
@RequiredArgsConstructor
public class MomentSearchReconciler implements Reconciler&lt;Reconciler.Request&gt; {

    private static final String FINALIZER = "moment-search-protection";

    private final ExtensionClient client;

    @Override
    public Result reconcile(Request request) {
        client.fetch(Moment.class, request.name()).ifPresent(moment -&gt; {
            if (ExtensionUtil.isDeleted(moment)) {
                if (ExtensionUtil.removeFinalizers(moment.getMetadata(), Set.of(FINALIZER))) {
                    client.update(moment);
                }
                return;
            }
            ExtensionUtil.addFinalizers(moment.getMetadata(), Set.of(FINALIZER));
            client.update(moment);
        });
        return Result.doNotRetry();
    }

    @Override
    public Controller setupWith(ControllerBuilder builder) {
        return builder
            .extension(new Moment())
            .workerCount(1)
            .build();
    }
}</code></pre>
<ol start="2">
 <li>
  <p style="">为 <code>MomentSearchReconciler</code> 添加搜索文档扩展相关的内容：</p>
 </li>
</ol>
<pre collapsed="true"><code class="language-java">@Component
@RequiredArgsConstructor
public class MomentSearchReconciler implements Reconciler&lt;Reconciler.Request&gt; {

    private static final String FINALIZER = "moment-search-protection";

    private final ApplicationEventPublisher eventPublisher;

    private final ExtensionClient client;
    
    // Convert moment to Halo Search Document
    private final DocumentConverter converter;

    @Override
    public Result reconcile(Request request) {
        client.fetch(Moment.class, request.name()).ifPresent(moment -&gt; {
            if (ExtensionUtil.isDeleted(moment)) {
                if (ExtensionUtil.removeFinalizers(moment.getMetadata(), Set.of(FINALIZER))) {
                    // Delete the document index when deleting moment.
                    eventPublisher.publishEvent(
                        new HaloDocumentDeleteRequestEvent(this,
                            List.of(converter.haloDocId(moment)))
                    );
                    client.update(moment);
                }
                return;
            }
            ExtensionUtil.addFinalizers(moment.getMetadata(), Set.of(FINALIZER));
            
            var haloDoc = converter.convert(moment)
                .blockOptional().orElseThrow();
            // When moment is updated, add or update the document.
            eventPublisher.publishEvent(
                new HaloDocumentAddRequestEvent(this, List.of(haloDoc)));

            client.update(moment);
        });
        return Result.doNotRetry();
    }

    @Override
    public Controller setupWith(ControllerBuilder builder) {
        return builder
            .extension(new Moment())
            .workerCount(1)
            .build();
    }
}</code></pre>
<p style="">其中使用了 <code>DocumentConverter</code> ，用于将 <code>Moment</code> 转为 <code>Halo Search Document</code> 。关于 HaloDocument 的字段见 <a href="https://github.com/halo-dev/halo/blob/main/api/src/main/java/run/halo/app/search/HaloDocument.java">HaloDocument</a>。以下是需要注意的几个属性：</p>
<pre collapsed="true"><code class="language-java">/**
 * Document for search.
 */
@Data
public final class HaloDocument {
    /**
     * Metadata name of the corresponding extension.
     */
    @NotBlank
    private String metadataName;

    /**
     * Whether the document is published.
     * After setting it to false, visitors will not be able to search 
     * and will only be used for system internal search.
     */
    private boolean published;

    /**
     * Whether the document is recycled.
     */
    private boolean recycled;

    /**
     * Whether the document is exposed to the public.
     */
    private boolean exposed;
}</code></pre>
<ol start="3">
 <li>
  <p style="">实现 <code>HaloDocumentsProvider</code> 接口，用于重建索引时调用：</p>
 </li>
</ol>
<pre collapsed="true"><code class="language-java">
@Component
@RequiredArgsConstructor
public class MomentHaloDocumentsProvider implements HaloDocumentsProvider {

    public static final String MOMENT_DOCUMENT_TYPE = "moment.moment.halo.run";

    private final ReactiveExtensionClient client;

    private final DocumentConverter converter;

    @Override
    public Flux&lt;HaloDocument&gt; fetchAll() {
        var options = new ListOptions();
        var notDeleted = QueryFactory.isNull("metadata.deletionTimestamp");
        var approved = QueryFactory.equal("spec.approved", "true");
        options.setFieldSelector(FieldSelector.of(notDeleted).andQuery(approved));
        var pageRequest = createPageRequest();
        // make sure the moments are approved and not deleted.
        return client.listBy(Moment.class, options, pageRequest)
            .map(ListResult::getItems)
            .flatMapMany(Flux::fromIterable)
            .flatMap(converter::convert);
    }

    @Override
    public String getType() {
        return MOMENT_DOCUMENT_TYPE;
    }

    private PageRequest createPageRequest() {
        return PageRequestImpl.of(1, SEARCH_DEFAULT_PAGE_SIZE,
            Sort.by("metadata.creationTimestamp", "metadata.name"));
    }
}</code></pre>
<p style="">至此， Moment 插件已经适配了 Halo 搜索文档。之后使用搜索功能时，就能查找到 <code>Type</code> 为 <code>moment.moment.halo.run</code> 的内容了。</p>
<h2 style="" id="%E7%BB%93%E8%AF%AD">结语</h2>
<p style="">总体而言，Halo 在核心部分处理了搜索引擎的大部分工作，插件作者只需要关心如何将数据内容转换为 <code>Halo Search Document</code> ，以及何时新增、更新、删除文档即可。实现逻辑相对简单。</p>
<p style="">希望这篇文章能够帮助到想要开发新插件的用户！</p>
<p style=""></p>]]></description><guid isPermaLink="false">/archives/halo-cha-jian-kuo-zhan-sou-suo-yin-qing</guid><dc:creator>Takagi</dc:creator><category>Halo 插件开发</category><pubDate>Mon, 15 Jul 2024 17:15:53 GMT</pubDate></item><item><title><![CDATA[【Halo 主题】Sakura 食用说明（1.x 版本）]]></title><link>https://lixingyong.com/archives/halo%E4%B8%BB%E9%A2%98sakura%E9%A3%9F%E7%94%A8%E8%AF%B4%E6%98%8E</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=%E3%80%90Halo%20%E4%B8%BB%E9%A2%98%E3%80%91Sakura%20%E9%A3%9F%E7%94%A8%E8%AF%B4%E6%98%8E%EF%BC%881.x%20%E7%89%88%E6%9C%AC%EF%BC%89&amp;url=/archives/halo%E4%B8%BB%E9%A2%98sakura%E9%A3%9F%E7%94%A8%E8%AF%B4%E6%98%8E" width="1" height="1" alt="" style="opacity:0;">
<h1 id="前言">前言</h1>
<p>主题已经发布有半年之久才开始写使用手册，实在是抱歉各位！！！但相较于写使用文档，果然我还是更喜欢摸鱼~</p>
<p>本主题较复杂，因此上手略难一些，本次特意在珍贵的元旦假期内写出此篇文档，以便于帮助大家更好的上手此主题。</p>
<p>另外如果对主题有任何使用上的困惑，可以查看此文档或留言博主。</p>
<h1 id="开始">开始</h1>
<h2 id="安装-halo-cms系统">①安装 Halo CMS系统</h2>
<p>此处就不进行赘述了，相关文章实在是太多了。</p>
<p>可以参考如下文章帮助你快速开始 <a href="https://docs.halo.run/zh/install/linux">https://docs.halo.run/zh/install/linux</a></p>
<h2 id="安装-sakura-主题">②安装 Sakura 主题</h2>
<p>目前有<strong>离线安装及在线安装</strong>两种方式，推荐离线安装方式。</p>
<h3 id="离线安装">离线安装</h3>
<h4 id="下载主题">下载主题</h4>
<p>目前可以从 Github 上下载 Sakura 主题。</p>
<p>链接：<a href="https://github.com/LIlGG/halo-theme-sakura">https://github.com/LIlGG/halo-theme-sakura</a></p>
<p>建议下载发行版即可。下载完成之后为 .zip 文件。</p>
<h4 id="安装主题">安装主题</h4>
<p>进入 Halo 后台，点击导航菜单的外观选项</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609661073463-fbfcb00e-3abf-4d6e-a893-48886530c249.png&amp;size=m" alt="image.png"></p>
<p>点击主题标题最右侧的 “安装” 在弹出的 “安装主题” 对话框中，选择“本地上传”并使用 .ZIP 格式的主题压缩包即可自动安装主题。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609661357032-526ea641-72e1-4b5b-90a4-ed76a3df2bb2.png&amp;size=m" alt="image.png"></p>
<h3 id="在线安装">在线安装</h3>
<p>在线安装无须下载压缩包。同样的，在 Halo 的后台，选择导航栏的外观选项，然后点击主题标题最右侧的 “安装”。</p>
<p>不同于离线安装的是，在线安装时，在弹出的“安装主题”对话框中，需要选择“远程拉取”，如下</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609661736967-ba5e432f-70e5-4348-ad5d-4a5bd4bc2681.png&amp;size=m" alt="image.png"></p>
<p>先填写 Github 仓库地址为 Sakura 主题的地址：<a href="https://github.com/LIlGG/halo-theme-sakura">https://github.com/LIlGG/halo-theme-sakura</a>。</p>
<p>之后选择“获取版本”，建议使用发行版。如下图</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609662653545-ada1eb84-c54f-497a-b1fb-95e9c102bd0b.png&amp;size=m" alt="image.png"></p>
<p>下载即可！ 【在线安装可能不稳定，比较建议使用离线安装！另外如果使用者修改了主题，将会导致无法更新主题，需要特别注意！】</p>
<h1 id="了解-sakura-主题">了解 Sakura 主题</h1>
<blockquote>
 <p>本主题提供了较多的自定义选项，建议在使用主题之前，仔细阅读本教程，可以帮助你更好的使用它。</p>
</blockquote>
<h2 id="主题功能">主题功能</h2>
<h3 id="丰富的后台配置项">丰富的后台配置项</h3>
<p>本主题提供了各种位置的配置项，方便用户自定义主题。【配置项大多数是以功能区域来划分】</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609663946158-976342bd-535a-4c55-84ea-e67a6d725482.png&amp;size=m" alt="image.png"></p>
<p>对于一般用户而言，使用默认的主题配置已经足够。但也可以根据自己的需求调整配置。</p>
<h3 id="首页故障文本和头像">首页故障文本和头像</h3>
<p>主题首页支持故障文本与头像两种方式。如下图为故障文本</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609664395930-7fb30c38-65b8-4b8e-aba0-bf091df9165e.png&amp;size=m" alt="image.png"></p>
<p>若你想改变首页显示，则可以在主题配置的“第一屏”中找到。</p>
<h3 id="首页背景视频">首页背景视频</h3>
<p>主题支持首页背景视频，且在 1.3.0 版本之后，将使用个人 API 提供流视频（流视频指无论多大的视频，都能无加载立即播放，之后边播放边缓存的视频播放方式）的功能。当然也支持本地 MP4 格式的视频。并且当用户填写了流视频又填写了本地视频之后，将优先播放本地视频。</p>
<p>※ 流视频首次加载可能出现卡顿或者直接停止播放的现象，属于正常情况，可以过段时间再尝试</p>
<p>如需进行背景视频相关设置，可在主题配置的 “第一屏” 中找到对应的配置项</p>
<h3 id="多级菜单及菜单图标">多级菜单及菜单图标</h3>
<h4 id="多级菜单">多级菜单</h4>
<p><strong>当前主题支持多级菜单</strong>。多级菜单需要在 Halo 后台 “外观 -&gt; 菜单” 中添加。 【注：主题在设计阶段，父菜单无论是否有子菜单都可以设置单独的跳转链接，如果不想让父菜单跳转，那么设置父菜单的链接地址为 <code>#</code> 即可】 halo 1.4.2 版本之前，可以在编辑里面选中父级菜单即可。</p>
<p>halo 1.4.2 版本之后，将支持菜单拖拽为子菜单，如下图所示</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage-605239ec0abd41509b65cadbe958518d.png&amp;size=m" alt="image.png"></p>
<h4 id="菜单图标">菜单图标</h4>
<p>默认支持 <strong>fontawesome 图标</strong>，如果想增加菜单图标，需要在编辑菜单时，在图标一行，写上对应的图标代码。例如</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage-4127f570027e44e98912165b9e9ac9e9.png&amp;size=m" alt="image.png"></p>
<p>图标代码如下：</p>
<pre><code>fa fa-fort-awesome faa-horizontal
</code></pre>
<p>其中 fa 必须存在，代表其为 fontawesome 图标。 fa-fort-awesome 为对应的字体图标名称，可以前往 <a href="http://www.fontawesome.com.cn/cheatsheet/">http://www.fontawesome.com.cn/cheatsheet/</a> 获取 faa-horizontal 代表鼠标移入时的动画效果，可以前往 <a href="https://www.51qianduan.com/article/view/4111.html">https://www.51qianduan.com/article/view/4111.html</a> 查看具体演示</p>
<h3 id="随机图">随机图</h3>
<p>在主题 1.3.0 版本之后，主题将支持随机图，随机图 API 将采用个人 API 提供服务。</p>
<h4 id="如何使用">如何使用</h4>
<p>随机封面图默认开启，如需关闭请在主题设置中的 “随机图” 中关闭即可。</p>
<p>随机首页图默认关闭，如需开启请在主题设置中的 “随机图” 中开启即可。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609665921680-5b1f21f9-8500-4b57-beb3-6546da5a46da.png&amp;size=m" alt="image.png"></p>
<p>【如果使用者已经为某文章/页面 设置过封面图，将优先使用设置的封面图】</p>
<h4 id="随机图获取范围及编号">随机图获取范围及编号</h4>
<p>随机图 API 使用的所有图片，由个人画廊提供：<a href="http://view.lixingyong.com/">https://view.lixingyong.com/</a> 。 随机图支持用户切换图片选取范围，可以根据个人需要进行选择，默认从画廊中所有公开图片中随机选择。【私密图片或私密账号无法获取到】</p>
<p><strong>个人画廊支持用户自定义上传图片，创建相册等</strong>，如需要添加个人图片入库，可以前往 <a href="http://view.lixingyong.com/">https://view.lixingyong.com/</a> 注册账号进行上传。<strong>入库数据非及时生效，需要 0 ~ 30 分钟的时间进行更新，关于入库数据的生效时间及其他注意事项，可以查看 [API开发（二）随机图片 API 设计思路]</strong>(<a href="https://lixingyong.com/2020/10/21/%E9%9A%8F%E6%9C%BA%E5%9B%BE%E7%89%87api">https://lixingyong.com/2020/10/21/%E9%9A%8F%E6%9C%BA%E5%9B%BE%E7%89%87api</a>)</p>
<h5 id="获取范围为用户">获取范围为用户</h5>
<p>当随机图获取范围为 “用户” 时，API 接口将会在某个用户下选择图片。此时，需要在范围编号中填写此用户的用户名。</p>
<p>可以前往 <a href="https://view.lixingyong.com/explore/recent/?list=users&amp;sort=date_desc">https://view.lixingyong.com/explore/recent/?list=users&amp;sort=date_desc</a> 来查看想要获取图片的用户名。如下所示</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609749649491-6c2c06a1-1571-45e4-aed9-c8310d03f1cb.png&amp;size=m" alt="image.png"></p>
<p>需要注意的是，用户名为 小写英文字母 + 下划线 + 数字 的组合。</p>
<h5 id="获取范围为分类">获取范围为分类</h5>
<p>当随机图获取范围为 “分类” 时，API 接口将会在某个分类下选择图片。此时，需要在范围编号中填写分类名。</p>
<p>对应分类名可以点击“探索”菜单中对应的分类来获得。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609749880588-ffbbef39-827d-4811-84d0-fb3f8d32b245.png&amp;size=m" alt="image.png"></p>
<h5 id="获取范围为相册">获取范围为相册</h5>
<p>当随机图获取范围为 “相册” 时，API 接口将会在某个相册下选择图片。此时，需要在范围编号中填写相册编号。</p>
<p>可以前往 <a href="https://view.lixingyong.com/explore/recent/?list=albums&amp;sort=date_desc&amp;page=1">https://view.lixingyong.com/explore/recent/?list=albums&amp;sort=date_desc&amp;page=1</a> 下来查看其他网友贡献的相册。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609750156919-5b05eb88-4ec3-40d8-8b48-8114ff28593a.png&amp;size=m" alt="image.png"></p>
<p>之后，可以点击某个具体的相册来查看相册编号，例如查看 “精美插图” 的编号</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609750245249-4fa0a522-5c8d-4eff-a82f-ac10636d064c.png&amp;size=m" alt="image.png"></p>
<h4 id="关闭页面文章随机图">关闭页面/文章随机图</h4>
<p>若开启随机图之后，但对于某个文章/页面不想使用随机图，则可以在发布时，使用 <strong>元数据</strong> 的方式来取消。</p>
<p>如下所示</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609667704809-bde6ca0d-1b26-4f48-96fd-eaf8d24d4e24.png&amp;size=m" alt="image.png"></p>
<p>K 必须为 ri，代表为随机图的元数据。 V 必须为 true 或 false，否则会报错！</p>
<h3 id="夜间模式">夜间模式</h3>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F01%2F05%2F1609665401631-4699b1f3-7774-4e2f-9c18-99f222dcb848.png&amp;size=m" alt="image.png"></p>
<p>本主题支持夜间模式，在页面的右下角可以切换夜间模式及白天模式。也可以在主题设置的“主题切换”内，设置默认主题及关闭主题切换功能等。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage-06f4a314fd1e465b8dbb3e969fb47d4d.png&amp;size=m" alt="image.png"></p>
<h3 id="心情页">心情页</h3>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%281%29-41bb81f088f34406988c926812b17eab.png&amp;size=m" alt="image.png"></p>
<p>本主题提供了额外的日志页面。需要使用的可以在 Halo 后台增加心情菜单 <code>/journals</code>&nbsp;来使用。</p>
<p>对于日志页面的主题配置，需要在主题设置的 “日志页” 中去控制。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%282%29-dd5d53f5a64e4b78a2d22d87c41eeeaa.png&amp;size=m" alt="image.png"></p>
<h3 id="图库页">图库页</h3>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%283%29-b017b173835c4743a84365a804f02e7e.png&amp;size=m" alt="image.png"></p>
<p>本主题提供了图库页面。需要使用的可以在 Halo 后台增加图库菜单 <code>/photos</code>&nbsp;来访问。图片需要在 Halo 后台进行配置。</p>
<p>特别的，本主题预设了多种展现图片的形式，<strong>比较推荐使用瀑布流</strong>。可以在主题设置的“相册页”进行配置</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%284%29-4f295005cdbb45518b4e75317238f0d7.png&amp;size=m" alt="image.png"></p>
<h3 id="友链自定义页面">友链自定义页面</h3>
<p>由于 Halo 自带的友链界面，无法在最开始写上自己想说的话，因此本主题额外提供了一个友链的自定义页面供大家使用。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%285%29-013e095fecf44ddc9a09f37cfed09ccf.png&amp;size=m" alt="image.png"></p>
<p>需要使用的，可以在 Halo 后台的自定义页面，新建一个任意的自定义页面。在发布时，选择“自定义模板”为 links 即可。如下所示：</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%286%29-11993110b48a4f2aa63bd3a4f4bfcefd.png&amp;size=m" alt="image.png"></p>
<h3 id="文章及页面目录">文章及页面目录</h3>
<p>本主题默认对所有文章及自定义页面内容启用 TOC 目录。具体效果如下</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%287%29-d104747f7134402390c36597cde6f19c.png&amp;size=m" alt="image.png"></p>
<p>尽管是对所有页面和自定义页面都生效，但可以采用在后台发布文章、页面时，<strong>增加 元数据</strong> 的方式，来规定某个页面或文章不使用目录。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%288%29-e6717747728c46b499ab4e01b1bf65aa.png&amp;size=m" alt="image.png"></p>
<p>其中元数据的 K 必须为 toc，而 V 只能为 true 或者 false，否则将产生错误。</p>
<p>若想针对于目录的全局配置，则可以在<code>主题配置的 -&gt; 文章页</code> 进行修改。</p>
<h3 id="目录展开级别">目录展开级别</h3>
<p>本主题中，目录的展开级别是可以调整的，对于全局的目录级别，可以前往<code>主题设置 -&gt; 文章页 -&gt; 目录标题展开级别</code> 进行设置。 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F02%2F25%2Fimage.png&amp;size=m" alt="image.png"></p>
<p>另外的，如果想对单独的文章/页面设置目录级别，则可以在发布文章、页面时，<strong>使用元数据</strong> 的方式来定义其目录级别。【为文章、页面设置的目录级别优先级高于全局设置】 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2F2021%2F02%2F25%2Fimage0866399a767c314c.png&amp;size=m" alt="image0866399a767c314c.png"></p>
<p>其中元数据的 K 必须为 tocDepth, 而 V 需要为 0 - 5 分别对应<code>主题设置 -&gt; 文章页 -&gt; 目录标题展开级别</code>从上到下的等级。</p>
<h3 id="代码高亮">代码高亮</h3>
<p>本主题强制启用代码块高亮功能，并默认提供了七种代码高亮风格供使用。可以在主题设置的“文章页”中进行更换。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%289%29-89e6ea828ff54032ad563cb09635f6f9.png&amp;size=m" alt="image.png"></p>
<p>尽管主题启用了自动语言检测的功能，但还是建议使用者在编写 Markdown 的时候，对代码块录入对应的语法名称。如</p>
<pre><code class="language-shell">```js
```
</code></pre>
<h3 id="类-mac-风格代码块">类 Mac 风格代码块</h3>
<p>本主题使用 Mac 风格代码块，并且可以对代码进行一键复制。【也可以放大哦】</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%2810%29-824f8e8f59014a098e28f3bc96c5b48d.png&amp;size=m" alt="image.png"></p>
<h3 id="标签云标签颜色自定义">标签云、标签颜色自定义</h3>
<p>本主题支持标签云及标签颜色随机自定义。如果不需要可以进入主题设置“标签及分类页”中进行修改</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%2811%29-3f528bb8309e42d2a63c80fc5a3f691f.png&amp;size=m" alt="image.png"></p>
<h3 id="分类雷达">分类雷达</h3>
<p>本主题支持分类雷达及分类颜色随机自定义。如果不需要可以进入主题设置“标签及分类页”进行修改</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%2812%29-1b70d2bab64e4fd0ba512adab7d6acda.png&amp;size=m" alt="image.png"></p>
<h3 id="邮件模板自定义">邮件模板自定义</h3>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%2813%29-921d262939a94c3fbe63686f9a214825.png&amp;size=m" alt="image.png"></p>
<h4 id="自定义头部图片">自定义头部图片</h4>
<p>在主题设置 - 其他 - 邮件回复模块图片 中修改。</p>
<h3 id="静态资源本地云端切换">静态资源本地/云端切换</h3>
<p>在 1.3.0 版本之后，静态资源支持本地或云端两种读取方式。如用户对本地静态资源文件有所替换，则建议使用本地资源。默认将采用云端资源。</p>
<p>需要更改的用户，可以前往主题设置“其他”内的“资源使用 CDN” 进行更换</p>
<h2 id="插件功能">插件功能</h2>
<p>由于 Halo 暂时没有插件功能，因此前端只能采用约定大于配置的方式，来实现伪插件的功能。本主题定义了几种常用的插件，用来完善主题功能。</p>
<h3 id="评论组件">评论组件</h3>
<p>本主题使用的是定制化的评论组件，组件地址：<a href="https://github.com/LIlGG/halo-comment-sakura">https://github.com/LIlGG/halo-comment-sakura</a> 但实际上主题并不限制使用哪个评论组件，如果有更换的需求，可以在主题设置的“评论组件”中，修改评论模块 JS 来更换。</p>
<p>如下为当前的评论组件，支持各种小表情。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%2814%29-714f6453b7a749c2b56c129a2116829f.png&amp;size=m" alt="image.png"></p>
<p>评论组件仅支持 markdown 格式 【注：目前评论组件暂无什么额外配置，后续还需要进行部分改动】</p>
<h3 id="音乐插件">音乐插件</h3>
<p>本主题采用 aplayer.js 作为音乐的基础插件，搭配 个人 API 实现背景音乐功能。默认关闭，如需开启，则需要前往主题设置中的“插件功能”，打开“开启 aplayer 插件”的功能。</p>
<p>额外的，如果还想要开启左下角的浮动背景音乐，则还需要前往主题设置中的“背景音乐”配置启用。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%2815%29-15c975e71abb484385b65f28619873c4.png&amp;size=m" alt="image.png"></p>
<h4 id="如何在文章页面内增加音乐列表">如何在文章/页面内增加音乐列表？？</h4>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%2816%29-58f0831faa6944729f187ca3fba48140.png&amp;size=m" alt="image.png"></p>
<p>在文章/页面内增加音乐列表，需要至少开启主题设置中的“插件功能 - 开启 aplayer功能”。开启之后，在页面中想要插入音乐的地方，复制如下 HTML 即可。</p>
<pre><code class="language-html">&lt;div 
     id="aplayer" 
     style="z-index: 100;" 
     class="aplayer" 
     data-id="2638142102" 
     data-server="netease" 
     data-type="playlist" 
     data-fixed="false" 
     data-preload="auto" 
     data-order="list"
     data-autoplay="false"
     data-theme="orange"&gt;
&lt;/div&gt;
</code></pre>
<blockquote>
 <p>data-id：歌单 ID。目前只支持歌单 data-server：歌曲提供服务地，目前只支持网易云，即 netease data-type：目标 ID 类型，目前只支持歌单，即 playlist data-fixed：是否为吸底模式，页内的都要为 false data-preload：是否自动加载，看需求通常选择 none：不自动加载 或 auto：自动加载 data-order：循环方式，可以有下面几种。list：顺序，random：随机 data-theme：主题颜色。 data-autoplay：是否自动播放</p>
</blockquote>
<p>其他 aplayer 配置可以查看 <a href="https://aplayer.js.org/#/home?id=options">https://aplayer.js.org/#/home?id=options</a> 可以使用 data-{option_name} 来传入任何 aplayer 支持的属性</p>
<h3 id="看板娘">看板娘</h3>
<p>本主题默认集成了看板娘功能，但对其原版功能未做大的改动。具体可以查看 <a href="https://github.com/LIlGG/halo-live2d">https://github.com/LIlGG/halo-live2d</a> <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Flixingyong.com%2Fupload%2F2021%2F01%2Fimage%2520%2817%29-a2115ba884f24ce694dbd0553d5ee7bf.png&amp;size=m" alt="image.png"></p>
<p>默认会关闭看板娘，开启看板娘会占用一部分内存，根据需求前往 <code>插件功能 -&gt; 开启 Live2D 插件</code>进行开启。为了移动端的流畅功能，移动端将自动禁用看板娘功能，望理解！</p>
<p>可以前往主题设置中的“看板娘”以及“插件功能”，来设置看板娘的所有功能。</p>
<h3 id="数学公式">数学公式</h3>
<p>应用户要求，在 1.3.0 版本之后，系统将集成 Mathjax 用来渲染数学公式，但数学公式需要加载多个耗费资源的 JS，考虑到不是人人都需要，因此默认关闭。</p>
<p>若有相应的需求，可以前往 “主题设置 -&gt; 插件功能 -&gt; 开启 Mathjax 数学公式插件” 中进行开启/关闭操作。另外在 1.3.1 版本之后，还需要在文章，元数据中填写 K -&gt; math V -&gt; true 来开启对应文章的 Mathjax，否则即便开启全局 Mathjax 也不会生效</p>
<h3 id="国际化">国际化</h3>
<p>在 1.3.0 版本之后，主题增加了前端国际化功能，用来根据用户的不同需求，展示不同的语言。</p>
<p>国际化功能默认强制开启，但可以根据需求设置语言，默认自动。用户可前往 “主题设置 -&gt; 其他 -&gt; 主题语言” 中进行修改</p>
<p>如果用户想增加/修改国际化语言字段，请查阅国际化文档。</p>
<h2 id="与原版主题的说明">与原版主题的说明</h2>
<p>本主题的原版主题，为 WordPress 上的 Sakura 主题。十分感谢 mashirozx 大佬制作如此漂亮的主题，让我等“有机可乘”，非常感谢！</p>
<p>不过目前本版主题除了样式部分，其他地方却与原主题完全不一致。因为后续的功能，基本都属于参照原主题的样式从零编写的。因而大家会发现，在功能、样式等方面或多或少有一些差距。</p>
<p>我希望做到的是，站在巨人的肩膀上，将主题做的更好，更完善，尽管目前来说不如原主题。但我还是会尽自己最大的努力做好本主题，至少不让前辈蒙羞！</p>
<p>希望各位大大能够给个 star，你们的支持是我最大的动力~</p>
<p><a href="https://github.com/LIlGG/halo-theme-sakura">https://github.com/LIlGG/halo-theme-sakura</a></p>]]></description><guid isPermaLink="false">/archives/halo%E4%B8%BB%E9%A2%98sakura%E9%A3%9F%E7%94%A8%E8%AF%B4%E6%98%8E</guid><dc:creator>Takagi</dc:creator><category>开源项目</category><pubDate>Mon, 4 Jan 2021 16:23:00 GMT</pubDate></item><item><title><![CDATA[API开发（二）随机图片 API 设计思路]]></title><link>https://lixingyong.com/archives/%E9%9A%8F%E6%9C%BA%E5%9B%BE%E7%89%87api</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=API%E5%BC%80%E5%8F%91%EF%BC%88%E4%BA%8C%EF%BC%89%E9%9A%8F%E6%9C%BA%E5%9B%BE%E7%89%87%20API%20%E8%AE%BE%E8%AE%A1%E6%80%9D%E8%B7%AF&amp;url=/archives/%E9%9A%8F%E6%9C%BA%E5%9B%BE%E7%89%87api" width="1" height="1" alt="" style="opacity:0;">
<h1 id="目的">目的</h1>
<p>尽管对于一个博客而言，最主要的是文章的内容质量，相较而言，作为装饰的图片，就显得不是那么重要了。但实际上大多数时候，图片才是决定博客美观的最重要因素。只不过当一个博客内的图片过多时，就会让用户无法去选择，因此最好开发一个通用的，随机图片API，来减少用户找图片的烦恼。</p>
<p>基于以上需求，因此我决定开发一个随机图片 API，用来为所有的用户提供一个方便快捷的自动图片API。</p>
<h1 id="要求">要求</h1>
<p>基于先决条件，图片 API 需要有以下特点</p>
<ul>
 <li>返回 JSON 格式，可以根据用户的需求返回张数，所以应该为数组。然后应该包含一些基础信息，所以最好为对象数组</li>
 <li>图片可以由用户上传，但不可删除</li>
 <li>可以指定是哪个用户，哪个相册，哪个分类下的图片</li>
 <li>用户可以选择按顺序展示图片还是随机展示（<del>这是不是就不算随机图了</del>）</li>
 <li>对于某个用户请求同样的数据，在一定时间内应该保持同一组</li>
</ul>
<h1 id="设计">设计</h1>
<p>接口暂定为 <strong>api/images</strong></p>
<table>
 <thead>
  <tr>
   <th>参数名</th>
   <th>参数值</th>
   <th>参数说明</th>
   <th>是否必填</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>type</td>
   <td>urls（图片链接列表）（默认）
    <br>
    list （除了图片的列表，例如用户、相册、分类）
    <br>
    detail（详细信息）
    <br>
    url（直接获取某个随机图片或指定图片）</td>
   <td>接口二级分类</td>
   <td>是</td>
  </tr>
  <tr>
   <td>itype</td>
   <td>image（图片）
    <br>
    user（用户）
    <br>
    album（相册）（默认）
    <br>
    category（分类）</td>
   <td>接口三级分类</td>
   <td>否</td>
  </tr>
  <tr>
   <td>id</td>
   <td>1. 当 type 为 urls 时，根据&nbsp; itype，有不同的情况：
    <br>
    itype 为 user 时，为用户名
    <br>
    itype 为 album 时，相册编号
    <br>
    itype 为 category 时，分类urlKey
    <br>
    当itype 不填时，从图片列表随机读取
    <br>
    2. 当 type 为 list 时， 不需要ID
    <br>
    3. 当 type 为 detail 时，根据 itype，有不同的情况：
    <br>
    itype 为 user 时，为用户名
    <br>
    itype 为 album 时，相册编号
    <br>
    itype 为 category 时，分类urlKey
    <br>
    itype 为 image 时，为图片编号
    <br>
    4. 当 type 为 url 时，根据 itype 的不同，具有不同的状态
    <br>
    itype 为 user 时，为用户号。接口将在用户中随机一个图片返回
    <br>
    itype 为 album 时，为相册编号。接口将在相册中随机一个图片返回
    <br>
    itype 为 category 时，为分类 url_key，接口将在分类中随机一个图片返回
    <br>
    itype 为 image 时，为图片编号，接口将返回指定的图片</td>
   <td>接口请求标识</td>
   <td>否</td>
  </tr>
  <tr>
   <td>kind</td>
   <td>random（随机）
    <br>
    order（顺序）</td>
   <td>图片是随机从图库中查找，还是按顺序返回，当 type 为 urls 时生效</td>
   <td>否</td>
  </tr>
  <tr>
   <td>count</td>
   <td>10（默认值）</td>
   <td>返回的图片数量，当 type 为 urls 时生效</td>
   <td>否</td>
  </tr>
  <tr>
   <td>satrt</td>
   <td>0（默认值）</td>
   <td>图片开始位置，仅当 kind 为 order 时生效。若开始值大于图片数量，则查询最后 count 个</td>
   <td>否</td>
  </tr>
 </tbody>
</table>
<h1 id="接口">接口</h1>
<p>截止 2020/12/1 起，接口已经上线，访问地址 <a href="https://api.lixingyong.com/api/images">https://api.lixingyong.com/api/images</a> ~<del>但未集成在主题中。另外接口使用文档也未完善。静待。【除 url 功能】</del>~【sakura 1.3.0 已实装】</p>
<h1 id="缓存">缓存</h1>
<p>为了提供更快速的服务，系统将默认启用 redis 缓存。其中，针对于图片服务，redis 缓存机制如下：</p>
<ol>
 <li>对于同一个 referer 下，同一个请求，将启用 1 小时的数据缓存配置。（可以采用 r 随机字符串的方式来取消此缓存）</li>
 <li>对于同一个数据库查询方式，将启用 30 分钟的数据缓存配置。（此缓存无法取消，固定 30 分钟，此期间可能会导致图库数据无法及时更新）</li>
</ol>
<h1 id="webp">webp</h1>
<p>使用接口获取的图片，默认将全部支持 Webp 格式，在保证减少网络请求大小的同时不降低图片质量。考虑到用户可能需要原图，因此支持在 Webp 格式的图片上保存下载原图。</p>
<h1 id="cdn">cdn</h1>
<p>尽管我服务器的带宽还可以，但也许还是比较慢的。因此对于随机图 API，我将使用我个人的 CDN 来进行加速支持。</p>
<h1 id="上传支持">上传支持</h1>
<p>以往的随机图 API，用户都无法上传/使用自己心仪的图片。而本随机图 API 将采用我的<a target="_blank" href="https://view.lixingyong.com"> Chevereto 图床</a>，便于支持用户心仪图片的上传、检索、下载等功能。任何想使用自己心仪图片的用户，都可以上传图片至图床，然后使用随机图 API 来进行读取。（由于缓存原因，在 0 - 30 分钟内，上传的图片可能不会刷新，静待即可。）</p>
<h2 id="要求-1">要求</h2>
<p>为了防止垃圾图片，因此需要用户注册，然后验证邮箱之后才可使用。我保证不会恶意删除任何用户的图片。
 <br>
 目前将不会开启图片审核，除非有任何违规图片的出现。
 <br>
 【<strong>API 将不会读取任何私密图片</strong>】</p>
<h1 id="补充功能">补充功能</h1>
<h2 id="20201211-补充">2020/12/11 补充</h2>
<ol>
 <li>补充 type 为 url 的情况。
  <br>
  当 type 为 url 时，根据 itype 的不同，具有不同的状态
  <br>
  • itype 为 user 时，为用户号。接口将在用户中随机一个图片返回
  <br>
  • itype 为 album 时，为相册编号。接口将在相册中随机一个图片返回
  <br>
  • itype 为 category 时，为分类 url_key，接口将在分类中随机一个图片返回
  <br>
  • itype 为 image 时，为图片编号，接口将返回指定的图片
  <br>
  当 type 为 url 时，新增一个图片类型选项。 暂定 qn
  <br>
  • 当 qn 为 1 时，返回中等大小图
  <br>
  • 当 qn 为 2 时，返回缩略图
  <br>
  • 其他情况均返回原图</li>
 <li>补充 type 为 urls 时，图片返回的接口增加三种类型的图片。
  <br>
  a. 原图
  <br>
  b. 中等大小
  <br>
  c. 缩略图</li>
</ol>]]></description><guid isPermaLink="false">/archives/%E9%9A%8F%E6%9C%BA%E5%9B%BE%E7%89%87api</guid><dc:creator>Takagi</dc:creator><category>API 开发</category><pubDate>Wed, 21 Oct 2020 09:46:48 GMT</pubDate></item><item><title><![CDATA[XXL-JOB（分布式任务调度）]]></title><link>https://lixingyong.com/archives/xxl-job</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=XXL-JOB%EF%BC%88%E5%88%86%E5%B8%83%E5%BC%8F%E4%BB%BB%E5%8A%A1%E8%B0%83%E5%BA%A6%EF%BC%89&amp;url=/archives/xxl-job" width="1" height="1" alt="" style="opacity:0;">
<h2 id="概述">概述</h2>
<p>XXL-JOB是一个轻量级的分布式任务调度平台，使用较为方便且下载后立即可以使用，非常方便。由于目前公司项目涉及到分布式，因此选择接入XXL-JOB来进行作业调度。</p>
<blockquote>
 <p>注：本文基于<strong>XXL-JOB-2.2.1-SNAPSHOT</strong> 版本，2.2.x版本较之前版本有很大区别，需要注意的是以下几点。</p>
 <ol>
  <li>调度中心升级至SpringBoot2.x版本，因此系统要求JDK1.8+</li>
  <li>完全移除旧版注解 JobHandler，目前使用基于方法的 xxlJob</li>
 </ol>
</blockquote>
<h2 id="特性">特性</h2>
<p>实际上，由于XXL-JOB本身为国人开发，因此教程非常直观，本来不打算过多介绍，但由于我使用的时候恰好网站崩了，所以还是写一篇教程来记录一下。以下特性也为官方说明。</p>
<blockquote></blockquote>
<ul>
 <li>1、简单：支持通过Web页面对任务进行CRUD操作，操作简单，一分钟上手；</li>
 <li>2、动态：支持动态修改任务状态、启动/停止任务，以及终止运行中任务，即时生效；</li>
 <li>3、调度中心HA（中心式）：调度采用中心式设计，“调度中心”自研调度组件并支持集群部署，可保证调度中心HA；</li>
 <li>4、执行器HA（分布式）：任务分布式执行，任务"执行器"支持集群部署，可保证任务执行HA；</li>
 <li>5、注册中心: 执行器会周期性自动注册任务, 调度中心将会自动发现注册的任务并触发执行。同时，也支持手动录入执行器地址；</li>
 <li>6、弹性扩容缩容：一旦有新执行器机器上线或者下线，下次调度时将会重新分配任务；</li>
 <li>7、路由策略：执行器集群部署时提供丰富的路由策略，包括：第一个、最后一个、轮询、随机、一致性HASH、最不经常使用、最近最久未使用、故障转移、忙碌转移等；</li>
 <li>8、故障转移：任务路由策略选择"故障转移"情况下，如果执行器集群中某一台机器故障，将会自动Failover切换到一台正常的执行器发送调度请求。</li>
 <li>9、阻塞处理策略：调度过于密集执行器来不及处理时的处理策略，策略包括：单机串行（默认）、丢弃后续调度、覆盖之前调度；</li>
 <li>10、任务超时控制：支持自定义任务超时时间，任务运行超时将会主动中断任务；</li>
 <li>11、任务失败重试：支持自定义任务失败重试次数，当任务失败时将会按照预设的失败重试次数主动进行重试；其中分片任务支持分片粒度的失败重试；</li>
 <li>12、任务失败告警；默认提供邮件方式失败告警，同时预留扩展接口，可方便的扩展短信、钉钉等告警方式；</li>
 <li>13、分片广播任务：执行器集群部署时，任务路由策略选择"分片广播"情况下，一次任务调度将会广播触发集群中所有执行器执行一次任务，可根据分片参数开发分片任务；</li>
 <li>14、动态分片：分片广播任务以执行器为维度进行分片，支持动态扩容执行器集群从而动态增加分片数量，协同进行业务处理；在进行大数据量业务操作时可显著提升任务处理能力和速度。</li>
 <li>15、事件触发：除了"Cron方式"和"任务依赖方式"触发任务执行之外，支持基于事件的触发任务方式。调度中心提供触发任务单次执行的API服务，可根据业务事件灵活触发。</li>
 <li>16、任务进度监控：支持实时监控任务进度；</li>
 <li>17、Rolling实时日志：支持在线查看调度结果，并且支持以Rolling方式实时查看执行器输出的完整的执行日志；</li>
 <li>18、GLUE：提供Web IDE，支持在线开发任务逻辑代码，动态发布，实时编译生效，省略部署上线的过程。支持30个版本的历史版本回溯。</li>
 <li>19、脚本任务：支持以GLUE模式开发和运行脚本任务，包括Shell、Python、NodeJS、PHP、PowerShell等类型脚本;</li>
 <li>20、命令行任务：原生提供通用命令行任务Handler（Bean任务，"CommandJobHandler"）；业务方只需要提供命令行即可；</li>
 <li>21、任务依赖：支持配置子任务依赖，当父任务执行结束且执行成功后将会主动触发一次子任务的执行, 多个子任务用逗号分隔；</li>
 <li>22、一致性：“调度中心”通过DB锁保证集群分布式调度的一致性, 一次任务调度只会触发一次执行；</li>
 <li>23、自定义任务参数：支持在线配置调度任务入参，即时生效；</li>
 <li>24、调度线程池：调度系统多线程触发调度运行，确保调度精确执行，不被堵塞；</li>
 <li>25、数据加密：调度中心和执行器之间的通讯进行数据加密，提升调度信息安全性；</li>
 <li>26、邮件报警：任务失败时支持邮件报警，支持配置多邮件地址群发报警邮件；</li>
 <li>27、推送maven中央仓库: 将会把最新稳定版推送到maven中央仓库, 方便用户接入和使用;</li>
 <li>28、运行报表：支持实时查看运行数据，如任务数量、调度次数、执行器数量等；以及调度报表，如调度日期分布图，调度成功分布图等；</li>
 <li>29、全异步：任务调度流程全异步化设计实现，如异步调度、异步运行、异步回调等，有效对密集调度进行流量削峰，理论上支持任意时长任务的运行；</li>
 <li>30、跨语言：调度中心与执行器提供语言无关的 RESTful API 服务，第三方任意语言可据此对接调度中心或者实现执行器。除此之外，还提供了 “多任务模式”和“httpJobHandler”等其他跨语言方案；</li>
 <li>31、国际化：调度中心支持国际化设置，提供中文、英文两种可选语言，默认为中文；</li>
 <li>32、容器化：提供官方docker镜像，并实时更新推送dockerhub，进一步实现产品开箱即用；</li>
 <li>33、线程池隔离：调度线程池进行隔离拆分，慢任务自动降级进入"Slow"线程池，避免耗尽调度线程，提高系统稳定性；</li>
 <li>34、用户管理：支持在线管理系统用户，存在管理员、普通用户两种角色；</li>
 <li>35、权限控制：执行器维度进行权限控制，管理员拥有全量权限，普通用户需要分配执行器权限后才允许相关操作；</li>
</ul>
<h2 id="快速入门">快速入门</h2>
<p>本项目是一个Maven项目，因此下载之后，使用IDE打开，利用maven编译即可。</p>
<h3 id="1源码地址">1、源码地址</h3>
<blockquote>
 <p>git地址：<a href="https://github.com/xuxueli/xxl-job">https://github.com/xuxueli/xxl-job</a>
  <br>
  码云地址（国内推荐）：<a href="https://gitee.com/xuxueli0323/xxl-job">https://gitee.com/xuxueli0323/xxl-job</a></p>
</blockquote>
<h3 id="2文档地址">2、文档地址</h3>
<blockquote>
 <p>中文文档：<a href="http://www.xuxueli.com/xxl-job/#/">http://www.xuxueli.com/xxl-job/#/</a>
  <br>
  英文文档：<a href="http://www.xuxueli.com/xxl-job/en/#/">http://www.xuxueli.com/xxl-job/en/#/</a></p>
</blockquote>
<p>从git/码云上克隆项目到本地，使用maven编译即可。</p>
<h3 id="3源码结构">3、源码结构</h3>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1597304720796-71f3dfb2-c725-4c3b-b9f3-85c967c27cd6.png%23align%3Dleft%26display%3Dinline%26height%3D377%26margin%3D%255Bobject%2520Object%255D%26name%3Dimage.png%26originHeight%3D753%26originWidth%3D859%26size%3D94751%26status%3Ddone%26style%3Dnone%26width%3D429.5&amp;size=m" alt="image.png"></p>
<h3 id="4初始化数据库">4、初始化数据库</h3>
<p>目前XXL-JOB支持MySQL数据库， 初始化SQL脚本在源目录 <code>/doc/db/tables_xxl_job.sql</code>&nbsp;下。会生成8张数据库表。
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1597305507303-90861c4a-d1b4-4364-8391-13f8f780d1ac.png%23align%3Dleft%26display%3Dinline%26height%3D123%26margin%3D%255Bobject%2520Object%255D%26name%3Dimage.png%26originHeight%3D245%26originWidth%3D278%26size%3D8931%26status%3Ddone%26style%3Dnone%26width%3D139&amp;size=m" alt="image.png"></p>
<h3 id="5部署调度中心">5、部署调度中心</h3>
<p>调度中心为源码中的 <code>xxl-job-admin</code>&nbsp;工程，该工程可以让我们以图形化的方式统一管理调度任务。</p>
<h4 id="调度中心配置">①、调度中心配置</h4>
<p>调度中心的配置文件地址：<code>xxl-job-admin/src/main/resources/application.properties</code>&nbsp;</p>
<pre><code class="language-yaml">### web 调度中心项目的访问端口与路径
server.port=8080
server.servlet.context-path=/xxl-job-admin

### actuator 健康端点路径，默认不开启
management.server.servlet.context-path=/actuator
management.health.mail.enabled=false

### resources 静态资源配置
spring.mvc.servlet.load-on-startup=0
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/

### freemarker 模板文件配置
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.suffix=.ftl
spring.freemarker.charset=UTF-8
spring.freemarker.request-context-attribute=request
spring.freemarker.settings.number_format=0.##########

### mybatis 配置mybatis的mapper路径
mybatis.mapper-locations=classpath:/mybatis-mapper/*Mapper.xml
#mybatis.type-aliases-package=com.xxl.job.admin.core.model

### xxl-job, datasource 数据库配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job?useUnicode=true&amp;characterEncoding=UTF-8&amp;autoReconnect=true&amp;serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
### 当前driver-class为5.7+的数据源，如果为5.7-修改为com.mysql.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

### datasource-pool 连接池配置
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.maximum-pool-size=30
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=HikariCP
spring.datasource.hikari.max-lifetime=900000
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.connection-test-query=SELECT 1

### xxl-job, email 配置报警邮箱
spring.mail.host=smtp.qq.com
spring.mail.port=25
spring.mail.username=xxx@qq.com
spring.mail.from=xxx@qq.com
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

### xxl-job, access token token，用于与执行器加密交互数据
xxl.job.accessToken=

### xxl-job, i18n (default is zh_CN, and you can choose "zh_CN", "zh_TC" and "en")
xxl.job.i18n=zh_CN

## xxl-job, triggerpool max size
xxl.job.triggerpool.fast.max=200
xxl.job.triggerpool.slow.max=100

### xxl-job, log retention days
xxl.job.logretentiondays=30
</code></pre>
<p>当前配置文件一般来说，只需要修改第25行的数据库配置。以及第43行的报警邮箱即可。</p>
<h4 id="部署调度中心">②、部署调度中心</h4>
<p>调度中心项目为一个 SpringBoot 项目，因此只需要在设置好配置文件后，直接运行 <code>XxlJobAdminApplication</code>&nbsp; 即可。</p>
<h4 id="访问调度中心">③、访问调度中心</h4>
<p>在浏览器中输入 <a href="http://127.0.0.1:8080/xxl-job-admin，然后输入默认用户名和密码（admin/123456），即可进入管理页面">http://127.0.0.1:8080/xxl-job-admin，然后输入默认用户名和密码（admin/123456），即可进入管理页面</a>
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1597306689535-29408af2-8fea-4ab4-8681-5bf7ebf23924.png&amp;size=m" alt="image.png"></p>
<h4 id="调度中心的集群实现可选">④、调度中心的集群实现（可选）</h4>
<p>按照官方的说明，想要实现调度中心的集群部署，需要有以下几点</p>
<ul>
 <li>DB配置一样</li>
 <li>登录账号一样</li>
 <li>集群机器时钟保持一致</li>
</ul>
<p>建议采用Nginx为调度中心集群做负载均衡，分配域名。
 <br>
 调度中心访问、执行器回调配置、调用API服务等操作均通过该域名进行。</p>
<p>由于连接的为同一个数据库，因此不会产生重复执行的问题。集群中采用谁先启动谁为主的方式。</p>
<h3 id="6部署执行器项目">6、部署执行器项目</h3>
<p>项目中有各种版本的执行器项目， 本文中采用 SpringBoot 版本的执行器。对应执行器为源码中的 <code>xxl-job-executor-sample-springboot</code>&nbsp;工程。
 <br>
 执行器可以使用默认的，也可以使用已有的项目作为执行器。默认的直接启动即可，没什么难度，因而本文采用新的 SpringBoot 项目来创建一个执行器，也可以用已经存在的项目按以下步骤改成一个执行器。</p>
<h4 id="创建一个新的springboot项目略">①、创建一个新的SpringBoot项目（略）</h4>
<h4 id="添加maven依赖">②、添加Maven依赖</h4>
<p>在新创建好的SpringBoot项目的pom.xml里加入xxl-job的公共依赖</p>
<pre><code class="language-xml">&lt;!-- xxl-job-core --&gt;
&lt;dependency&gt;
			&lt;groupId&gt;com.xuxueli&lt;/groupId&gt;
			&lt;artifactId&gt;xxl-job-core&lt;/artifactId&gt;
      &lt;version&gt;2.2.1-SNAPSHOT&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<h4 id="配置执行器">③、配置执行器</h4>
<p>当前新建的SpringBoot项目采用yml作为配置文件，因此需要在 application.yml 中添加如下配置</p>
<pre><code class="language-yaml">server:
  #项目端口号
  port: 8081
logging:
  #日志文件
  config: classpath:logback.xml

xxl:
  job:
    admin:
      #调度中心部署跟地址：如调度中心集群部署存在多个地址则用逗号分隔。
      #执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调"。
      addresses: http://127.0.0.1:8080/xxl-job-admin

    #分别配置执行器的名称、ip地址、端口号
    #注意：如果配置多个执行器时，防止端口冲突
    executor:
      appname: demo
      ip: 127.0.0.1
      address:
      port: 9999
      #执行器运行日志文件存储的磁盘位置，需要对该路径拥有读写权限
      logpath: /data/applogs/xxl-job/jobhandler
      #执行器Log文件定期清理功能，指定日志保存天数，日志文件过期自动删除。限制至少保持3天，否则功能不生效；
      #-1表示永不删除
      logretentiondays: -1
    accessToken:
</code></pre>
<h4 id="载入配置文件">④、载入配置文件</h4>
<p>在示例的SpringBoot项目中，找到 <code>xxl-job-executor-samples/xxl-job-executor-sample-springboot/src/main/java/com/xxl/job/executor/core/config/XxlJobConfig.java</code>&nbsp;，将 XxlJobConfig.java 复制到自己的项目中，如下图
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1597309997189-4c846e37-c60b-42ba-aec1-dd0946091ab5.png%23align%3Dleft%26display%3Dinline%26height%3D228%26margin%3D%255Bobject%2520Object%255D%26name%3Dimage.png%26originHeight%3D455%26originWidth%3D392%26size%3D27485%26status%3Ddone%26style%3Dnone%26width%3D196&amp;size=m" alt="image.png"></p>
<h4 id="创建任务">⑤、创建任务</h4>
<p>在目前我所使用的2.2.1版本，已经抛弃原有的JobHandler注解，推荐使用基于方法的 xxlJob 注解。</p>
<pre><code class="language-java">package com.example.demo.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 任务示例（Bean模式）
 *
 * 开发步骤：
 * 1、在Spring Bean实例中，开发Job方法，方式格式要求为 "public ReturnT&lt;String&gt; execute(String param)"
 * 2、为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobLogger.log" 打印执行日志；
 */
@Component
public class JobHandlerDemo {
    private static Logger logger = LoggerFactory.getLogger(JobHandlerDemo.class);

    /**
     * 简单任务示例（Bean模式）
     */
    @XxlJob("demoJobHandler")
    public ReturnT&lt;String&gt; demoJobHandler(String param) throws Exception {
        XxlJobLogger.log("XXL-JOB, Hello World.");

        for (int i = 0; i &lt; 5; i++) {
            XxlJobLogger.log("beat at:" + i);
            TimeUnit.SECONDS.sleep(2);
        }
        return ReturnT.SUCCESS;
    }
}
</code></pre>
<p>当前的XxlJob注解有一个value： demoJobHandler 这个值会在调度中心的可视化界面中进行配置。</p>
<h4 id="执行器项目集群可选">⑥、执行器项目集群（可选）</h4>
<p>执行器也支持集群部署，对于执行器也有几点要求和建议。</p>
<ul>
 <li>执行器回调地址（xxl.job.admin.addresses）需要保持一致；执行器根据该配置进行执行器自动注册等操作</li>
 <li>同一个执行器集群内AppName（xxl.job.executor.appname）需要保持一致；调度中心根据该配置动态发现不同集群的在线执行器列表</li>
</ul>
<h3 id="7在调度中心中配置执行器">7、在调度中心中配置执行器</h3>
<p>调度中心在第 5 步中已经配置完成，直接启动即可。执行器也已经在第 6 步中配置完成，直接启动即可。目前都启动一个就行。</p>
<h4 id="配置执行器-1">①、配置执行器</h4>
<p>点击执行器管理 -&gt; 新增，弹出如下界面
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1597312122951-a16e6840-305e-418d-9ecb-c8640e662d36.png&amp;size=m" alt="image.png"></p>
<blockquote>
 <p>参数介绍：
  <br>
  AppName：对于每个<strong>执行器集群</strong>的唯一标识AppName，执行器会周期性以AppName通过心跳的方式为对象进行自动注册。
  <br>
  名称：执行器的名称，为了方便阅读
  <br>
  注册方式：调度中心获取执行器集群地址的方式
  <br>
  自动注册：执行器周期性的自动进行注册，调度中心通过底层注册表可以动态发现执行器的地址
  <br>
  手动录入：人工手动录入执行器的地址，多个地址之间用英文逗号（,）分隔
  <br>
  机器地址：“注册方式”为“手动录入”时可填，支持人工维护执行器的地址信息</p>
</blockquote>
<h4 id="创建调度任务">②、创建调度任务</h4>
<p>点击任务管理 -&gt; 新增，弹出如下界面
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1597312992193-e2f0e06c-3bac-48f6-8062-7c18a4581a62.png%23align%3Dleft%26display%3Dinline%26height%3D472%26margin%3D%255Bobject%2520Object%255D%26name%3Dimage.png%26originHeight%3D943%26originWidth%3D1920%26size%3D157805%26status%3Ddone%26style%3Dnone%26width%3D960&amp;size=m" alt="image.png"></p>
<blockquote>
 <p>参数介绍：
  <br>
  执行器：任务绑定的执行器。每个任务必须绑定一个执行器。
  <br>
  路由策略：当执行器集群部署时，提供丰富的路由策略
  <br>
  FIRST（第一个）：固定选择第一个机器；
  <br>
  LAST（最后一个）：固定选择最后一个机器；
  <br>
  ROUND（轮询）
  <br>
  RANDOM（随机）：随机选择在线的机器；
  <br>
  CONSISTENT_HASH（一致性HASH）：每个任务按照Hash算法固定选择某一台机器，且所有任务均匀散列在不同机器上；
  <br>
  LEAST_FREQUENTLY_USED（最不经常使用）：使用频率最低的机器优先被选举；
  <br>
  LEAST_RECENTLY_USED（最近最久未使用）：最久为使用的机器优先被选举；
  <br>
  FAILOVER（故障转移）：按照顺序依次进行心跳检测，第一个心跳检测成功的机器选定为目标执行器并发起调度；
  <br>
  BUSYOVER（忙碌转移）：按照顺序依次进行空闲检测，第一个空闲检测成功的机器选定为目标执行器并发起调度；
  <br>
  SHARDING_BROADCAST(分片广播)：广播触发对应集群中所有机器执行一次任务，同时系统自动传递分片参数；可根据分片参数开发分片任务；
  <br>
  运行模式：
  <br>
  BEAN模式：任务以JobHandler方式维护在执行器端；需要结合 "JobHandler" 属性匹配执行器中任务；
  <br>
  GLUE模式(Java)：任务以源码方式维护在调度中心；该模式的任务实际上是一段继承自IJobHandler的Java类代码并 "groovy" 源码方式维护，它在执行器项目中运行，可使用@Resource/@Autowire注入执行器里中的其他服务；
  <br>
  GLUE模式(Shell)：任务以源码方式维护在调度中心；该模式的任务实际上是一段 "shell" 脚本；
  <br>
  GLUE模式(Python)：任务以源码方式维护在调度中心；该模式的任务实际上是一段 "python" 脚本；
  <br>
  GLUE模式(PHP)：任务以源码方式维护在调度中心；该模式的任务实际上是一段 "php" 脚本；
  <br>
  GLUE模式(NodeJS)：任务以源码方式维护在调度中心；该模式的任务实际上是一段 "nodejs" 脚本；
  <br>
  GLUE模式(PowerShell)：任务以源码方式维护在调度中心；该模式的任务实际上是一段 "PowerShell" 脚本；
  <br>
  阻塞处理策略：调度过于密集执行器来不及处理时的处理策略；
  <br>
  单机串行（默认）：调度请求进入单机执行器后，调度请求进入FIFO队列并以串行方式运行；
  <br>
  丢弃后续调度：调度请求进入单机执行器后，发现执行器存在运行的调度任务，本次请求将会被丢弃并标记为失败；
  <br>
  覆盖之前调度：调度请求进入单机执行器后，发现执行器存在运行的调度任务，将会终止运行中的调度任务并清空队列，然后运行本地调度任务；
  <br>
  任务超时时间：支持自定义任务超时时间，任务运行超时将会主动中断任务；
  <br>
  负责人：任务的负责人；
  <br>
  任务参数：任务执行所需的参数，多个参数时用逗号分隔，任务执行时将会把多个参数转换成数组传入；
  <br>
  任务描述：任务的描述信息，便于任务管理；
  <br>
  Cron：触发任务执行的Cron表达式；
  <br>
  JobHandler：运行模式为 "BEAN模式" 时生效，对应执行器中新开发的JobHandler类“@JobHandler”注解自定义的value值；
  <br>
  子任务ID：每个任务都拥有一个唯一的任务ID(任务ID可以从任务列表获取)，当本任务执行结束并且执行成功时，将会触发子任务ID所对应的任务的一次主动调度。</p>
</blockquote>
<blockquote>
 <p>失败重试次数：支持自定义任务失败重试次数，当任务失败时将会按照预设的失败重试次数主动进行重试；</p>
</blockquote>
<blockquote>
 <p>报警邮箱：任务调度失败时邮件通知的邮箱地址，支持配置多邮箱地址，配置多个邮箱地址时用逗号分隔；</p>
</blockquote>
<h4 id="启动任务">③、启动任务</h4>
<p>任务配置完成后，就可以立即执行或者启动了。</p>
<h4 id="imagepng"><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1597314556609-5b0b2c93-96d8-4688-bfc8-0a002a4848e8.png%23align%3Dleft%26display%3Dinline%26height%3D472%26margin%3D%255Bobject%2520Object%255D%26name%3Dimage.png%26originHeight%3D943%26originWidth%3D1920%26size%3D117469%26status%3Ddone%26style%3Dnone%26width%3D960&amp;size=m" alt="image.png"></h4>
<h3 id="8调度日志">8、调度日志</h3>
<p>任务执行之后，我们可以在 调度日志 中，查看日志
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1597314689223-3bd67cde-e19b-4687-ad89-05178baac27c.png%23align%3Dleft%26display%3Dinline%26height%3D472%26margin%3D%255Bobject%2520Object%255D%26name%3Dimage.png%26originHeight%3D943%26originWidth%3D1920%26size%3D156578%26status%3Ddone%26style%3Dnone%26width%3D960&amp;size=m" alt="image.png">
 <br>
 点击操作，可以查看执行的详细日志
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1597314773956-efc91f29-bd4a-4b6d-bb86-d6d0b8681dca.png%23align%3Dleft%26display%3Dinline%26height%3D472%26margin%3D%255Bobject%2520Object%255D%26name%3Dimage.png%26originHeight%3D943%26originWidth%3D1920%26size%3D110312%26status%3Ddone%26style%3Dnone%26width%3D960&amp;size=m" alt="image.png">
 <br>
 【注：只有通过 <code>XxlJobLogger.log()</code>&nbsp;代码的方式才可以打印日志到上面】</p>
<h2 id="参考资料">参考资料</h2>
<p><a href="https://www.cnblogs.com/ysocean/p/10541151.html">分布式任务调度平台XXL-JOB搭建教程</a></p>]]></description><guid isPermaLink="false">/archives/xxl-job</guid><dc:creator>Takagi</dc:creator><category>开源项目</category><category>经验宝宝</category><pubDate>Fri, 14 Aug 2020 02:21:41 GMT</pubDate></item><item><title><![CDATA[Mybatis 一对多查询 分页问题]]></title><link>https://lixingyong.com/archives/mybatis</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=Mybatis%20%E4%B8%80%E5%AF%B9%E5%A4%9A%E6%9F%A5%E8%AF%A2%20%E5%88%86%E9%A1%B5%E9%97%AE%E9%A2%98&amp;url=/archives/mybatis" width="1" height="1" alt="" style="opacity:0;">
<h2 id="背景">背景</h2>
<p>之前给公司做的管理系统，今天被测出来，前台展示的分页数量和实际数量不符合，导致前台分页有误！（这么大的BUG竟然没发现，我也是服了自己了）
 <br>
 本项目数据库使用MySql，插件有如下两个</p>
<blockquote>
 <p>MyBatis
  <br>
  MyBatisPlus 分页插件</p>
</blockquote>
<h2 id="分析">分析</h2>
<h3 id="产生bug的地方">产生BUG的地方</h3>
<p>下方是未修改之前的SQL，通过多表连接查询一对多的数据</p>
<pre><code class="language-sql"># 修改前的SQL
SELECT
	u.*,
	r.role_id,
	r.role_name 
FROM
	sys_user AS u
	LEFT JOIN sys_user_role AS ur ON u.user_id = ur.user_id
	LEFT JOIN sys_role AS r ON ur.role_id = r.role_id 
ORDER BY
	u.user_id
</code></pre>
<p>该SQL查询出的信息如下图
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.nlark.com%2Fyuque%2F0%2F2020%2Fpng%2F1387674%2F1594368055652-b9fd77a8-e9a4-4acb-aad0-9c1af732389c.png%23align%3Dleft%26display%3Dinline%26height%3D105%26margin%3D%255Bobject%2520Object%255D%26name%3Dimage.png%26originHeight%3D210%26originWidth%3D1248%26size%3D37943%26status%3Ddone%26style%3Dnone%26width%3D624&amp;size=m" alt="image.png">
 <br>
 可以看出，这里查询出了7条数据。<strong>对于同一个主表，如果在子表中拥有多个关联时，就会查询出多条。</strong>
 <br>
 然后，使用查询出的结果，在后台使用 MyBatils 的 collection 进行一对多的处理。代码如下</p>
<pre><code class="language-xml">    &lt;resultMap type="com.xxx.modules.sys.entity.SysUserEntity" id="sysDetailUserMap"&gt;
        &lt;id property="userId" column="user_id" /&gt;
        &lt;result property="userName" column="user_name" /&gt;
        &lt;result property="loginName" column="login_name"/&gt;
        &lt;result property="mobile" column="mobile" /&gt;
        &lt;result property="email" column="email" /&gt;
        &lt;result property="sts" column="sts" /&gt;
        &lt;result property="regOrgId" column="reg_org_id" /&gt;
        &lt;result property="regOrgName" column="org_name" /&gt;
        &lt;result property="regTenantId" column="reg_tenant_id" /&gt;
        &lt;result property="regTenantName" column="tenant_name" /&gt;
        &lt;result property="createTime" column="create_time" /&gt;
        &lt;collection property="roles" ofType="com.xxx.modules.sys.entity.SysRoleEntity"&gt;
            &lt;id  property="roleId" column="role_id" /&gt;
            &lt;result property="roleName" column="role_name" /&gt;
        &lt;/collection &gt;
    &lt;/resultMap&gt;
</code></pre>
<p>经过这样，然后将查询的结果发送到前端，最终获取到的JSON结构如下所示</p>
<pre><code class="language-json">{
    "msg":"操作成功",
    "code":0,
    "page":{
        "totalCount":7, // 这里总数为SQL中查询的数据
        "pageSize":10,
        "totalPage":1,
        "currPage":1,
        "list":[{},{},{},{},{}] // 查询出的数据又是经过mybatis处理后的数据
    }
}
</code></pre>
<p>这里就可以看出，导致前台分页总数和实际展示的数量不一致的问题，就是分页总数与MyBatis数据不一致造成的。
 <br>
 似乎在MyBatis处理前，分页插件先查询了count，共查询7条纪录，之后再由MyBatis进行处理，然后处理完毕就剩5条纪录。</p>
<h3 id="产生bug的原因">产生BUG的原因</h3>
<p>既然产生了BUG，那就要理解其产生的原因。既然是分页插件和MyBaits的问题，那么就从这两个地方入手。
 <br>
 我所使用的是MyBatisPlus的分页插件，先了解一下它的分页实现原理吧。通过跟踪分析代码，观察它的实现方法</p>
<pre><code class="language-java">// SQL拦截的地方
public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler)PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
    	// 解析SQL
        this.sqlParser(metaObject);
        MappedStatement mappedStatement = (MappedStatement)metaObject.getValue("delegate.mappedStatement");
    	// 验证是否为SELECT操作，并且不为存储过程
        if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType() &amp;&amp; StatementType.CALLABLE != mappedStatement.getStatementType()) {
            BoundSql boundSql = (BoundSql)metaObject.getValue("delegate.boundSql");
            Object paramObj = boundSql.getParameterObject();
            IPage&lt;?&gt; page = null;
            // 验证参数值是否为page对象，如果参数值为Map，则从Map中读取page对象
            if (paramObj instanceof IPage) {
                page = (IPage)paramObj;
            } else if (paramObj instanceof Map) {
                Iterator var8 = ((Map)paramObj).values().iterator();

                while(var8.hasNext()) {
                    Object arg = var8.next();
                    if (arg instanceof IPage) {
                        page = (IPage)arg;
                        break;
                    }
                }
            }
			// 当page不存在或者size小于0的情况下，不进行分页
            if (null != page &amp;&amp; page.getSize() &gt;= 0L) {
                if (this.limit &gt; 0L &amp;&amp; this.limit &lt;= page.getSize()) {
                    page.setSize(this.limit);
                }

                String originalSql = boundSql.getSql();
                Connection connection = (Connection)invocation.getArgs()[0];
                DbType dbType = StringUtils.isNotEmpty(this.dialectType) ? DbType.getDbType(this.dialectType) : JdbcUtils.getDbType(connection.getMetaData().getURL());
                if (page.isSearchCount()) {
                    SqlInfo sqlInfo = SqlParserUtils.getOptimizeCountSql(page.optimizeCountSql(), this.countSqlParser, originalSql);
                    // 使用sql查询结果总数
                    this.queryTotal(this.overflow, sqlInfo.getSql(), mappedStatement, boundSql, page, connection);
                    if (page.getTotal() &lt;= 0L) {
                        return null;
                    }
                }
				// 将原始SQL和page拼接起来
                String buildSql = concatOrderBy(originalSql, page);
                DialectModel model = DialectFactory.buildPaginationSql(page, buildSql, dbType, this.dialectClazz);
                Configuration configuration = mappedStatement.getConfiguration();
                List&lt;ParameterMapping&gt; mappings = new ArrayList(boundSql.getParameterMappings());
                Map&lt;String, Object&gt; additionalParameters = (Map)metaObject.getValue("delegate.boundSql.additionalParameters");
                model.consumers(mappings, configuration, additionalParameters);
                metaObject.setValue("delegate.boundSql.sql", model.getDialectSql());
                metaObject.setValue("delegate.boundSql.parameterMappings", mappings);
                return invocation.proceed();
            } else {
                return invocation.proceed();
            }
        } else {
            return invocation.proceed();
        }
    }
</code></pre>
<p>由源码可知，<strong>分页插件在执行的时候，会先去查询所属SQL的总数，然后使用查到的总数进行分页，再与原始SQL拼接</strong>。
 <br>
 因此显而易见，问题出现在这里。</p>
<h3 id="如何解决bug">如何解决BUG</h3>
<p>BUG的解决办法有很多，我采用的是**先查询出主表中的数据总数，在执行collection时，再去使用子查询去查询一对多的关系。**<strong>此方法可能不适用与多对多查询</strong></p>
<h2 id="解决问题">解决问题</h2>
<h3 id="修改sql">修改SQL</h3>
<p>在mybatis中，修改查询SQL，使第一次查询只查询主表（不要查询一对多的关系）</p>
<pre><code class="language-xml">&lt;!-- 修改查询SQL，改为只查询主表 --&gt;
&lt;select id="selectUserPageList" resultMap="sysBaseUserMap"&gt;
  SELECT
    u.*
  FROM
    sys_user AS u
  ORDER BY
    u.user_id
&lt;/select&gt;

&lt;!-- 额外增加一个查询关联表的sql，其中user_id为子查询需要的条件，在collection中传入 --&gt;
&lt;select id="getUserRole" resultType="com.xxx.modules.sys.entity.SysRoleEntity"&gt;
	SELECT
    r.*
	FROM
    sys_role as r
	LEFT JOIN
    sys_user_role as ur
	ON
    r.role_id = ur.role_id
	WHERE
    ur.user_id = #{user_id}
&lt;/select&gt;
</code></pre>
<h3 id="修改collection">修改collection</h3>
<p>由于用到了子查询，因此需要修改原先的一对多处理方式，将其改为调用子查询</p>
<pre><code class="language-xml">&lt;resultMap type="com.xxx.modules.sys.entity.SysUserEntity" id="sysDetailUserMap"&gt;
	&lt;id property="userId" column="user_id" /&gt;
	&lt;result property="userName" column="user_name" /&gt;
	&lt;result property="loginName" column="login_name"/&gt;
	&lt;result property="mobile" column="mobile" /&gt;
	&lt;result property="email" column="email" /&gt;
	&lt;result property="sts" column="sts" /&gt;
	&lt;result property="regOrgId" column="reg_org_id" /&gt;
	&lt;result property="regOrgName" column="org_name" /&gt;
	&lt;result property="regTenantId" column="reg_tenant_id" /&gt;
	&lt;result property="regTenantName" column="tenant_name" /&gt;
	&lt;result property="createTime" column="create_time" /&gt;
	&lt;!-- column指向一个主表和子表的共有字段 --&gt;
  &lt;collection property="roles" ofType="com.xxx.modules.sys.entity.SysRoleEntity" column="user_id" select="getUserRole"&gt;
		&lt;id  property="roleId" column="role_id" /&gt;
		&lt;result property="roleName" column="role_name" /&gt;
	&lt;/collection &gt;
&lt;/resultMap&gt;
</code></pre>
<h3 id="查询结果">查询结果</h3>
<p>经过如上修改后，再次查询结果如下所示</p>
<pre><code class="language-json">{
    "msg":"操作成功",
    "code":0,
    "page":{
        "totalCount":5,
        "pageSize":10,
        "totalPage":1,
        "currPage":1,
        "list":[{},{},{},{},{}]
    }
}
</code></pre>
<h2 id="总结">总结</h2>
<p>这种方式可以解决一对多的问题。但针对于多对多问题还没有考虑过。做个记录</p>]]></description><guid isPermaLink="false">/archives/mybatis</guid><dc:creator>Takagi</dc:creator><category>经验宝宝</category><pubDate>Thu, 13 Aug 2020 06:23:39 GMT</pubDate></item><item><title><![CDATA[marked扩展语法（增加自定义表情）]]></title><link>https://lixingyong.com/archives/marked</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=marked%E6%89%A9%E5%B1%95%E8%AF%AD%E6%B3%95%EF%BC%88%E5%A2%9E%E5%8A%A0%E8%87%AA%E5%AE%9A%E4%B9%89%E8%A1%A8%E6%83%85%EF%BC%89&url=/archives/marked" width="1" height="1" alt="" style="opacity:0;" /><h2 id="背景">背景</h2>
<p>最近在移植WordPress的Sakura主题到Halo上（实际上只是参照样式重写了）。评论这里需要使用marked，Halo官方提供的表情不太适合我，且我早就想扩展一个带表情的marked了。因此正好借着这个机会，扩展一个带表情的marked。</p>
<p>后续也想扩展一下文章页面的marked，只是目前还没有插件。因此暂时先只改评论的即可，到时候通用一套语法即可。</p>
<p><strong>【注：当前文章大部分内容为分析，篇幅较长，如果不想看过程，直接跳转至<a href="#toc-head-12">扩展</a>即可】</strong></p>
<p>本篇文章基于如下内容</p>
<blockquote>
<p>marked.js：<a href="https://github.com/markedjs/marked">https://github.com/markedjs/marked</a><br />
说明文档：<a href="https://marked.js.org/#/README.md#README.md">https://marked.js.org/#/README.md#README.md</a></p>
</blockquote>
<h2 id="计划">计划</h2>
<p>根据我的计划，目前需要实现增加如下的功能</p>
<ul>
<li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" checked="checked" disabled="disabled" readonly="readonly" />&nbsp;扩展bilibili表情</li>
<li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" checked="checked" disabled="disabled" readonly="readonly" />&nbsp;扩展文字表情</li>
<li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" checked="checked" disabled="disabled" readonly="readonly" />&nbsp;扩展通用的Emoji表情</li>
<li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" readonly="readonly" />&nbsp;<del>增加通用的动态表情</del></li>
<li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" checked="checked" disabled="disabled" readonly="readonly" />&nbsp;将自定义的marked打包至npm</li>
</ul>
<h2 id="分析">分析</h2>
<p><strong>工欲善其事必先利其器。</strong> 扩展marked之前一定要了解清楚，如何扩展？是否拥有不修改源码的扩展方法？如果有如何扩展？如果没有，如何修改源码？抱着这个想法，我阅读了 marked.js 的官方文档以及源码。</p>
<h3 id="分析文档">分析文档</h3>
<p>在marked.js的<a href="https://marked.js.org/#/README.md">官方文档</a>中，我找到了 <a href="https://marked.js.org/#/USING_PRO.md">Extending Marked</a> 这章内容。</p>
<p>刚开始，我认为也许通过官方的扩展Marked文档即可实现，但仔细阅读之后，发现并没有那么简单。</p>
<p><strong>使用官方的扩展语法，只能扩展已有的渲染器方法</strong>。因为他们需要一个方法，例如  _heading(string src)  ，<em>进而通过该方法的返回值，来修改渲染样式</em>。_简而言之，官方的方法只能针对于已有的语法，然后修改其渲染方式，如渲染标题时，我们可以不使用默认的H1、H2，而改用div自定义渲染等等。即<strong>官方已经替你解析完毕，你要做的只是按照自己想要的方式去渲染即可</strong></p>
<p>而我们想实现的功能，是新添加一个解析，使用自己的解析语法，因此官方的这种方法不符合我们的要求。</p>
<p>继续翻看文章，在最后发现了如下内容<br />
<img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAyMC9wbmcvMTM4NzY3NC8xNTkyNTY5OTMxNzAwLTg1OTI4MjY2LTNmNTctNDViMS04NzY2LWFmZjk0ZTA0OGMxMS5wbmc" alt="image.png" /></p>
<p>这里可以看到大致流程，<strong>marked 使用 lexer 解析 markdown 文档成一个 tokens，然后使用 tokens 转换成 html</strong>。这是最重要的两步，那么问题来了，自定义的markdown语法如何解析成tokens？ 又如何从 tokens 渲染成 html？ 这里并没有提及，那么剩下的就只能从源码去看了。</p>
<h3 id="分析源码">分析源码</h3>
<h4 id="lexerjs">Lexer.js</h4>
<p>根据文档，marked使用Lexer将markdown转换成tokens，则直接查看 Lexer.js，下图是Lexer的方法<br />
<img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAyMC9wbmcvMTM4NzY3NC8xNTkyNzQzOTU4MTQzLTM2Njc0MzVmLTY0YjItNDRhMy05ZDVlLThlNTkzNTdkMzNiZC5wbmc" alt="image.png" /></p>
<p>其中获取Tokens分为了blockTokens/inlineTokens。根据方法名就能联想到分别是块级和行内的区别。由于我们想要新添加的表情属于行内，因此只需在inlineTokens中添加即可。</p>
<p>继续分析Lexer.js，inlineTokens方法的代码如下所示</p>
<pre><code class="language-javascript">inlineTokens(src, tokens = [], inLink = false, inRawBlock = false) {
    let token;

    while (src) {
      // escape
      if (token = this.tokenizer.escape(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      ......
    }
    return tokens;
</code></pre>
<p>src即为当前需要解析的字符串，然后当前方法循环解析字符串，并将字符串转换成token，之后保存在tokens中。<br />
很容易可以看出，当前方法使用了一个tokenizer对象将字符串解析成Token对象。该对象存在于Tokenizer.js中</p>
<h4 id="tokenizerjs">Tokenizer.js</h4>
<p>直接查看Tokenizer.js，找到如下代码</p>
<pre><code class="language-javascript">...... 
	escape(src) {
    const cap = this.rules.inline.escape.exec(src);
    if (cap) {
      return {
        type: 'escape',
        raw: cap[0],
        text: escape(cap[1])
      };
    }
  }
......
</code></pre>
<p>在这个方法中，很明显使用了 <a href="https://www.w3school.com.cn/js/jsref_exec_regexp.asp">exec()</a> 方法，该方法会检索字符串中的正则表达式的匹配，返回一个数组。如果未能找到，则返回null。<br />
所以此方法调用了rules对象，将字符串进行解析，然后返回一个数组。那么该对象内存的则应该是正则表达式。该对象存在于rules.js中，我们接着看rules.js。</p>
<h4 id="rulesjs">rules.js</h4>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAyMC9wbmcvMTM4NzY3NC8xNTkyNzQ1ODIzMDI3LTdjYjQ0OGRlLWFiNWMtNGIyNC05OTQxLTY4NWE1ZTdmZDhhYi5wbmc" alt="image.png" /><br />
很明显，这里即为保存各种正则表达式的地方。<br />
到这一步位置，将字符串转换为Tokens应该就很明确了。</p>
<p>那么，接下来的重点是，如果将Tokens渲染成html。前面也都没有看到有如何渲染的方法，那么，现在就需要我们找到调用Tokens的地方，根据代码，得到在marked.js中调用了Lexer.lex() 方法来获取Tokens。</p>
<h4 id="markedjs">marked.js</h4>
<p><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAyMC9wbmcvMTM4NzY3NC8xNTkyNzQ2MjI1MTA2LTRmNWI5YmUzLTc4ZTYtNDBhMy1iZjIyLWQzYzY5YjkwZTMyOS5wbmc" alt="image.png" /><br />
根据源码可以知道，在Parser.parse()中调用了tokens。</p>
<h4 id="parserjs">Parser.js</h4>
<pre><code class="language-javascript">  parseInline(tokens, renderer) {
    renderer = renderer || this.renderer;
    let out = '',
      i,
      token;

    const l = tokens.length;
    for (i = 0; i &lt; l; i++) {
      token = tokens[i];
      switch (token.type) {
        ......
        case 'escape': {
          out += renderer.text(token.text);
          break;
        }
      }
    }
    return out;
  }
</code></pre>
<p>parseInline即为行内的解析器。它按顺序循环Tokens，取出Token中保存的数据，而后调用renderer对象将token渲染成字符串并拼接起来。<br />
renderer对象在Renderer.js中。</p>
<h4 id="rendererjs">Renderer.js</h4>
<pre><code class="language-javascript">......  
heading(text, level, raw, slugger) {
    if (this.options.headerIds) {
      return '&lt;h'
        + level
        + ' id=&quot;'
        + this.options.headerPrefix
        + slugger.slug(raw)
        + '&quot;&gt;'
        + text
        + '&lt;/h'
        + level
        + '&gt;\n';
    }
    // ignore IDs
    return '&lt;h' + level + '&gt;' + text + '&lt;/h' + level + '&gt;\n';
  }
......
</code></pre>
<p>很容易可以看出来，Renderer就是渲染字符串的地方。使用Parse中解析的值然后渲染成字符串并返回。<br />
分析到这一步，整个思路就非常清楚了。</p>
<h3 id="分析总结">分析总结</h3>
<p>经过上面的分析，可以得出marked的渲染步骤，共有如下几个步骤</p>
<ol>
<li>编写正则表达式，用于将字符串解析成数组</li>
</ol>
<pre><code class="language-javascript">// rules.js
escape: /^\\([!&quot;#$%&amp;'()*+,\-./:;&lt;=&gt;?@\[\]\\^_`{|}~])/,
</code></pre>
<ol start="2">
<li>使用正则表达式解析目标字符串，并转化成token</li>
</ol>
<pre><code class="language-javascript">// Tokenizer.js
  escape(src) {
    const cap = this.rules.inline.escape.exec(src);
    if (cap) {
      return {
        type: 'escape',
        raw: cap[0],
        text: escape(cap[1])
      };
    }
  }
</code></pre>
<ol start="3">
<li>循环解析字符串，将其转换成tokens</li>
</ol>
<pre><code class="language-javascript">// Lexer.js
token = this.tokenizer.escape(src)
// 添加至tokens中
tokens.push(token);
</code></pre>
<ol start="4">
<li>将tokens按照特定的格式，使用渲染器进行渲染</li>
</ol>
<pre><code class="language-javascript">// Parser.js
out += renderer.text(token.text);
</code></pre>
<ol start="5">
<li>编写某个格式的HTML渲染</li>
</ol>
<pre><code class="language-javascript">// Renderer.js
  br() {
    return this.options.xhtml ? '&lt;br/&gt;' : '&lt;br&gt;';
  }
</code></pre>
<p>根据以上思路，就可以立马开工添加表情了。甚至以后如果有其他东西也很方便进行扩展。</p>
<h2 id="扩展">扩展</h2>
<p>由于我们添加的表情属于行内元素，因此均只考虑行内代码。</p>
<blockquote>
<p>bilibiliEmoji对应的markdown语法为： f(x)=∫(xxx)sec²xdx<br />
textEmoji对应的markdown语法为：<code>(⌒▽⌒)</code> <br />
codeEmoji对应的markdown语法为： :xxx: </p>
</blockquote>
<blockquote>
<p>其中xxx为表情的名字</p>
</blockquote>
<h3 id="编写正则">编写正则</h3>
<p>找到rules.js文件，在行内元素的对象中添加三条解析语句</p>
<pre><code class="language-javascript">// rules.js
// 正则表达式
const inline = {
  bilibiliEmoji: /^f\(x\)=∫\(([^A-Z]\w+?)\)sec²xdx/,
  textEmoji: /^`([^a-zA-Z]+?)`/,
  codeEmoji: /^:([^A-Z]\w+?):/
  ......
}
</code></pre>
<p>另外，还要确保不能将:，`以及f开头的字符串识别为文本，因此还需要改动一下text的正则表达式</p>
<pre><code class="language-javascript">const inline = {
  // 增加了!\[`:f*]
  text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\&lt;!\[`:f*]|\b_|$)|[^ ](?= {2,}\n))|(?= {2,}\n))/
}
// 如果开启了gfm，则还需要改动这个!\[`:f*]
inline.gfm = merge({}, inline.normal, {
  text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\&lt;!\[`:f*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&amp;'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&amp;'*+\/=?_`{\|}~-]+@))|(?= {2,}\n|[a-zA-Z0-9.!#$%&amp;'*+\/=?_`{\|}~-]+@))/
});
</code></pre>
<h3 id="转换字符串为token">转换字符串为Token</h3>
<p>找到Tokenizer.js，在构造函数下新增三条转换语句</p>
<pre><code class="language-javascript">//  Tokenizer.js
bilibiliEmoji(src) {
    const cap = this.rules.inline.bilibiliEmoji.exec(src);
    if (cap) {
      if (cap[0].length &gt; 1) {
        return {
          type: 'bilibiliEmoji',
          raw: cap[0],
          text: cap[1]
        };
      }
    }
  }

  textEmoji(src) {
    const cap = this.rules.inline.textEmoji.exec(src);
    if (cap) {
      if (cap[0].length &gt; 1) {
        return {
          type: 'textEmoji',
          raw: cap[0],
          text: cap[1]
        };
      }
    }
  }

  codeEmoji(src) {
    const cap = this.rules.inline.codeEmoji.exec(src);
    if (cap) {
      if (cap[0].length &gt; 1) {
        return {
          type: 'codeEmoji',
          raw: cap[0],
          text: cap[1]
        };
      }
    }
  }
</code></pre>
<h3 id="将表情token纳入tokens中">将表情token纳入tokens中</h3>
<p>在Lexer.js的inlineTokens中，判断字符串的类别并将token添加到tokens中去</p>
<pre><code class="language-javascript">// Lexer.js
  inlineTokens(src, tokens = [], inLink = false, inRawBlock = false) {
    let token;

    while (src) {
      // bilibili表情 f(x)=∫(xxx)sec²xdx
      if (token = this.tokenizer.bilibiliEmoji(src)) {
        src = src.substring(token.raw.length);
        if (token.type) {
          tokens.push(token);
        }
        continue;
      }

      // 文字表情
      if (token = this.tokenizer.textEmoji(src)) {
        src = src.substring(token.raw.length);
        if (token.type) {
          tokens.push(token);
        }
        continue;
      }

      // 帖吧表情/BBcodeEmoji
      if (token = this.tokenizer.codeEmoji(src)) {
        src = src.substring(token.raw.length);
        if (token.type) {
          tokens.push(token);
        }
        continue;
      }
      ......
    }
  }
</code></pre>
<h3 id="使用tokens进行解析">使用tokens进行解析</h3>
<p>在Parser.js中，循环tokens，并对每个token按照类型进行解析<br />
之后将获取到的html片段拼接</p>
<pre><code class="language-javascript">// Parser.js
parseInline(tokens, renderer) {
    renderer = renderer || this.renderer;
    let out = '',
      i,
      token;

    const l = tokens.length;
    for (i = 0; i &lt; l; i++) {
      token = tokens[i];
      switch (token.type) {
        case 'bilibiliEmoji': {
          out += renderer.bilibiliEmoji(token.text);
          break;
        }
        case 'textEmoji': {
          out += renderer.textEmoji(token.text);
          break;
        }
        case 'codeEmoji': {
          out += renderer.codeEmoji(token.text);
          break;
        }
        ......
      }
    }
  }
</code></pre>
<h3 id="生成html片段">生成HTML片段</h3>
<p>最后根据Parser.js中的解析，调用Renderer.js中renderer对象的方法渲染html片段</p>
<pre><code class="language-javascript">// Renderer.js
......
  bilibiliEmoji(text) {
    let href = text + '.png';
    href = cleanUrl(this.options.sanitize, this.options.bilibiliEmojiUrl, href);
    return '&lt;span class=&quot;emotion-inline emotion-item&quot;&gt;'
      + '&lt;img src=&quot;'
      + href
      + '&quot; class=&quot;img&quot;&gt;&lt;/span&gt;';
  }

  textEmoji(text) {
    return text;
  }

  codeEmoji(text) {
    let href = 'icon_' + text + '.gif';
    href = cleanUrl(this.options.sanitize, this.options.codeEmojiEmojiUrl, href);
    return '&lt;img src=&quot;'
     + href
     + '&quot; alt=&quot;:'
     + text
     + ':&quot; class=&quot;smilies&quot;&gt;';
  }
.....
</code></pre>
<h3 id="增加默认配置">增加默认配置</h3>
<p>在默认的配置文件（defaults.js）中，新增表情的地址，这样可以保证之后可以随意切换表情资源所在的地址</p>
<pre><code class="language-javascript">// defaults.js
function getDefaults() {
  return {
    baseUrl: null,
    breaks: false,
    gfm: true,
    headerIds: true,
    headerPrefix: '',
    highlight: null,
    langPrefix: 'language-',
    mangle: true,
    pedantic: false,
    renderer: null,
    sanitize: false,
    sanitizer: null,
    silent: false,
    smartLists: false,
    smartypants: false,
    tokenizer: null,
    walkTokens: null,
    xhtml: false,
    // 新增的表情地址
    bilibiliEmojiUrl: '****',
    codeEmojiEmojiUrl: '****'
  };
}
</code></pre>
<p>至此，解析已经完成。然后就可以对源码进行打包了。</p>
<h3 id="打包">打包</h3>
<p>先修改原有的package.json 中的配置为自己的，主要是name，desc，author，version<br />
也可以不修改，看个人。然后执行如下命令</p>
<pre><code class="language-shell">// 安装依赖
npm install
// 执行代码规范性检查（可选）
npm run test:lint
// 打包
npm run build
</code></pre>
<p>执行之后，生成的marked.min.js就可以直接使用了。<br />
当然了，我这里需要再发布到npm上，那就需要再执行下面的语句，将代码发布</p>
<pre><code class="language-shell">npm publish
</code></pre>
<p>至此，扩展就已经全部完成！</p>
]]></description><guid isPermaLink="false">/archives/marked</guid><dc:creator>Takagi</dc:creator><category>经验宝宝</category><pubDate>Mon, 22 Jun 2020 06:09:16 GMT</pubDate></item><item><title><![CDATA[Saiku源码完整搭建及问题解决方案]]></title><link>https://lixingyong.com/archives/saiku</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=Saiku%E6%BA%90%E7%A0%81%E5%AE%8C%E6%95%B4%E6%90%AD%E5%BB%BA%E5%8F%8A%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88&amp;url=/archives/saiku" width="1" height="1" alt="" style="opacity:0;">
<h2 id="saiku%E9%93%BE%E6%8E%A5%E5%9C%B0%E5%9D%80" tabindex="-1">Saiku链接地址</h2>
<blockquote>
 <p>官网：<a href="https://community.meteorite.bi/" target="_blank">https://community.meteorite.bi/</a>
  <br>
  GitHub：<a href="https://github.com/OSBI/saiku" target="_blank">https://github.com/OSBI/saiku</a>
  <br>
  文档：<a href="https://saiku-documentation.readthedocs.io/en/latest/#open-source" target="_blank">https://saiku-documentation.readthedocs.io/en/latest/#open-source</a></p>
</blockquote>
<p>本文中所使用的saiku版本为 3.x 版本</p>
<h2 id="%E5%AE%89%E8%A3%85%E6%95%99%E7%A8%8B" tabindex="-1">安装教程</h2>
<h3 id="%E4%B8%80-%E4%BD%BF%E7%94%A8git%E4%B8%8B%E8%BD%BD%E9%A1%B9%E7%9B%AE" tabindex="-1">一 使用git下载项目</h3>
<pre><code class="language-git">git clone git://github.com/OSBI/saiku.git
</code></pre>
<p><strong>【如果下载速度太感人，可以查看&nbsp;<a href="https://www.yuque.com/lixingyong/blog/mns7aw" target="_blank">git clone下载速度慢解决办法</a> 】</strong></p>
<h3 id="%E4%BA%8C-%E4%BF%AE%E6%94%B9maven%E4%BE%9D%E8%B5%96%E3%80%90%E9%87%8D%E3%80%91" tabindex="-1">二 修改maven依赖【重】</h3>
<p>saiku自带的maven仓库下载地址可能会出现各种问题，比如503等
 <br>
 以下是我修改后的maven仓库地址【方便起见只贴了修改的地方】</p>
<ol>
 <li>saiku/pom.xml</li>
</ol>
<pre><code class="language-xml">	&lt;distributionManagement&gt;
    &lt;!--
    &lt;repository&gt;
  		&lt;id&gt;utility&lt;/id&gt;
 			&lt;name&gt;utility-releases&lt;/name&gt;
 			&lt;url&gt;http://repo.meteorite.bi/repository/alabs-release-local/&lt;/url&gt;
 		&lt;/repository&gt;
 		&lt;snapshotRepository&gt;
 			&lt;id&gt;utility&lt;/id&gt;
 			&lt;name&gt;utility-snapshots&lt;/name&gt;
 			&lt;url&gt;http://repo.meteorite.bi/repository/alabs-snapshot-local/&lt;/url&gt;
 		&lt;/snapshotRepository&gt;
    --&gt;
	  &lt;repository&gt;
			&lt;id&gt;gitlab-maven&lt;/id&gt;
			&lt;url&gt;https://gitlab.com/api/v4/projects/14840263/packages/maven&lt;/url&gt;
	  &lt;/repository&gt;
	  &lt;snapshotRepository&gt;
      &lt;id&gt;gitlab-maven&lt;/id&gt;
			&lt;url&gt;https://gitlab.com/api/v4/projects/14840263/packages/maven&lt;/url&gt;
	  &lt;/snapshotRepository&gt;
	&lt;/distributionManagement&gt;

	&lt;pluginRepositories&gt;
    &lt;!--
  	&lt;pluginRepository&gt;
			&lt;id&gt;Analytical Labs Plugin Repo&lt;/id&gt;
			&lt;name&gt;Analytical Labs Repo-releases&lt;/name&gt;
			&lt;url&gt;http://repo.meteorite.bi/repository/alabs-release-local/&lt;/url&gt;
		&lt;/pluginRepository&gt;
    --&gt;
    &lt;pluginRepository&gt;
      &lt;id&gt;pentaho-third-party&lt;/id&gt;
      &lt;url&gt;http://nexus.pentaho.org/content/repositories/proxy-public-3rd-party-release/&lt;/url&gt;
    &lt;/pluginRepository&gt;
  &lt;/pluginRepositories&gt;

&lt;repositories&gt;
  &lt;!--
	&lt;repository&gt;
		&lt;id&gt;Analytical Labs Repo&lt;/id&gt;
		&lt;name&gt;Analytical Labs Repo-releases&lt;/name&gt;
		&lt;url&gt;http://repo.meteorite.bi/repository/alabs-release-local/&lt;/url&gt;
	&lt;/repository&gt;
	&lt;repository&gt;
		&lt;id&gt;Analytical Labs snapshots&lt;/id&gt;
		&lt;name&gt;Analytical Labs Repo-releases&lt;/name&gt;
		&lt;url&gt;http://repo.meteorite.bi/repository/alabs-snapshot-local/&lt;/url&gt;
	&lt;/repository&gt;
	--&gt;
  &lt;!-- 这里找到了四个有效的地址 --&gt;
	&lt;repository&gt;
		&lt;id&gt;gitlab-maven&lt;/id&gt;
		&lt;url&gt;https://gitlab.com/api/v4/projects/14840263/packages/maven&lt;/url&gt;
	&lt;/repository&gt;
	&lt;repository&gt;
		&lt;id&gt;saiku-group&lt;/id&gt;
		&lt;url&gt;https://nexus.nuiton.org/nexus/content/repositories/saiku-group/&lt;/url&gt;
	&lt;/repository&gt;
	&lt;repository&gt;
 		&lt;id&gt;pentaho-pentaho-third-party&lt;/id&gt;
		&lt;url&gt;http://nexus.pentaho.org/content/repositories/proxy-pentaho-public-release-group/&lt;/url&gt;
	&lt;/repository&gt;
	&lt;repository&gt;
		&lt;id&gt;pentaho-public-third-party&lt;/id&gt;
		&lt;url&gt;http://nexus.pentaho.org/content/repositories/proxy-public-3rd-party-release/&lt;/url&gt;
	&lt;/repository&gt;
  &lt;!-- 下面接省下的.... --&gt;
 &lt;/repositories&gt;

&lt;plugins&gt;
 	&lt;!-- 建议注释掉检查（我这边是注释掉了）
 &lt;plugin&gt;
		&lt;groupId&gt;org.owasp&lt;/groupId&gt;
		&lt;artifactId&gt;dependency-check-maven&lt;/artifactId&gt;
		&lt;version&gt;3.3.2&lt;/version&gt;
		&lt;executions&gt;
			&lt;execution&gt;
   			&lt;goals&gt;
					&lt;goal&gt;check&lt;/goal&gt;
				&lt;/goals&gt;
			&lt;/execution&gt;
		&lt;/executions&gt;
	&lt;/plugin&gt; --&gt;
  &lt;!-- 下面接省下的.... --&gt;
&lt;/plugins&gt;
</code></pre>
<ol start="2">
 <li>saiku\saiku-ui\pom.xml</li>
</ol>
<pre><code class="language-xml">&lt;repositories&gt;
  &lt;!--
	&lt;repository&gt;
		&lt;id&gt;jsdoctk1&lt;/id&gt;
		&lt;url&gt;http://jsdoctk-plugin.googlecode.com/svn/repo&lt;/url&gt;
	&lt;/repository&gt;
	--&gt;
  &lt;repository&gt;
		&lt;id&gt;saiku-group&lt;/id&gt;
		&lt;url&gt;https://nexus.nuiton.org/nexus/content/repositories/saiku-group/&lt;/url&gt;
	&lt;/repository&gt;
&lt;/repositories&gt;
&lt;pluginRepositories&gt;
  &lt;!--
	&lt;pluginRepository&gt;
		&lt;id&gt;jsdoctk2&lt;/id&gt;
		&lt;url&gt;http://jsdoctk-plugin.googlecode.com/svn/repo&lt;/url&gt;
	&lt;/pluginRepository&gt;
	&lt;pluginRepository&gt;
		&lt;name&gt;oss.sonatype.org&lt;/name&gt;
		&lt;id&gt;oss.sonatype.org&lt;/id&gt;
		&lt;url&gt;http://oss.sonatype.org/content/groups/public&lt;/url&gt;
	&lt;/pluginRepository&gt;
	--&gt;
  &lt;pluginRepository&gt;
		&lt;id&gt;saiku-group2&lt;/id&gt;
		&lt;url&gt;https://nexus.nuiton.org/nexus/content/repositories/saiku-group/&lt;/url&gt;
	&lt;/pluginRepository&gt;
&lt;/pluginRepositories&gt;
</code></pre>
<ol start="3">
 <li>saiku\saiku-bi-platform-plugin-p7\pom.xml</li>
</ol>
<pre><code class="language-xml">&lt;repositories&gt;
	&lt;!--
	&lt;repository&gt;
		&lt;id&gt;Analytical Labs Repo&lt;/id&gt;
		&lt;name&gt;Analytical Labs Repo-releases&lt;/name&gt;
		&lt;url&gt;http://repo.meteorite.bi/repository/alabs-release-local/&lt;/url&gt;
	&lt;/repository&gt;
	&lt;repository&gt;
		&lt;id&gt;Analytical Labs snapshots&lt;/id&gt;
		&lt;name&gt;Analytical Labs Repo-releases&lt;/name&gt;
		&lt;url&gt;http://repo.meteorite.bi/repository/alabs-snapshot-local&lt;/url&gt;
	&lt;/repository&gt;
		--&gt;
	&lt;repository&gt;
		&lt;id&gt;gitlab-maven&lt;/id&gt;
		&lt;url&gt;https://gitlab.com/api/v4/projects/14840263/packages/maven&lt;/url&gt;
	&lt;/repository&gt;
	&lt;repository&gt;
		&lt;id&gt;saiku-group&lt;/id&gt;
		&lt;url&gt;https://nexus.nuiton.org/nexus/content/repositories/saiku-group/&lt;/url&gt;
	&lt;/repository&gt;
	&lt;repository&gt;
		&lt;id&gt;pentaho-pentaho-third-party&lt;/id&gt;
		&lt;url&gt;http://nexus.pentaho.org/content/repositories/proxy-pentaho-public-release-group/&lt;/url&gt;
	&lt;/repository&gt;
	&lt;repository&gt;
		&lt;id&gt;pentaho-public-third-party&lt;/id&gt;
		&lt;url&gt;http://nexus.pentaho.org/content/repositories/proxy-public-3rd-party-release/&lt;/url&gt;
	&lt;/repository&gt;
  	&lt;!-- 下面接省下的.... --&gt;
  &lt;/repositories&gt;
</code></pre>
<ol start="4">
 <li>saiku\saiku-core\saiku-olap-util\src\main\java\mondrian\olap4j\SaikuMondrianHelper.java</li>
</ol>
<pre><code class="language-java"> public static String getMeasureGroup(Measure measure){
	if(isMondrian(measure)){
	  MondrianOlap4jMeasure	m = (MondrianOlap4jMeasure) measure;
/** 注释掉这里 */
/**	  try {
		return ((RolapBaseCubeMeasure) m.member).getMeasureGroup().getName();
	  }
	  catch(Exception e){
		return "";
	  }
	  catch(Error e2){
		return "";
	  }
	  */
	}
	return null;
  }
</code></pre>
<ol start="5">
 <li>saiku\saiku-core\saiku-olap-util\src\main\java\mondrian\rolap\DimensionLookup.java</li>
</ol>
<pre><code class="language-java">  public static boolean getHanger(RolapCubeDimension dim){
    /** 这里改成true即可 */
    return true;
  }
</code></pre>
<h3 id="%E4%B8%89-%E4%B8%8B%E8%BD%BDmaven%E4%BE%9D%E8%B5%96" tabindex="-1">三 下载maven依赖</h3>
<pre><code class="language-">// 在根目录下执行
mvn clean install -DskipTests
</code></pre>
<p>静静等待即可。
 <br>
 【如果提示mvn命令不存在，则需要先配置maven环境变量】
 <br>
 【如果改完上面的maven还报错，可以留言给我】</p>
<h3 id="%E5%9B%9B-%E5%8E%BB%E9%99%A4license%E9%AA%8C%E8%AF%81%E4%BF%A1%E6%81%AF%E3%80%90%E5%8F%AF%E9%80%89%E3%80%91" tabindex="-1">四 去除License验证信息【可选】</h3>
<p>去除License验证信息需要修改以下几处源码</p>
<ol>
 <li>saiku\saiku-core\saiku-web\src\main\java\org\saiku\web\rest\resources\License.java</li>
</ol>
<pre><code class="language-java">  /**
   * Get the saiku
   * @summary Get the Saiku License installed on the current server
   * @return A response containing a license object.
   */
  @GET
  @Produces({ "application/json" })
  public Response getLicense() {
 // 直接返回正确结果
//   try {
//     return Response.ok().entity(licenseUtils.getLicense()).build();
//   } catch (IOException | RepositoryException | ClassNotFoundException e) {
//     e.printStackTrace();
//   }
    return Response.serverError().build();
  }

</code></pre>
<ol start="2">
 <li>saiku\saiku-core\saiku-web\src\main\java\org\saiku\web\service\SessionService.java</li>
</ol>
<p>修改login，去掉验证代码</p>
<pre><code class="language-java">	/* (non-Javadoc)
	 * @see org.saiku.web.service.ISessionService#login(javax.servlet.http.HttpServletRequest, java.lang.String, java.lang.String)
	 */
	public Map&lt;String, Object&gt; login(HttpServletRequest req, String username, String password ) throws LicenseException {
	//	Object sl = null;
	//	String notice = null;
		HttpSession session = ((HttpServletRequest)req).getSession(true);
		session.getId();
		sessionRepo.setSession(session);
	//	try {
	//		sl = l.getLicense();
	//	} catch (Exception e) {
	//		log.debug("Could not process license", e);
	//		throw new LicenseException("Error fetching license. Get a free license from http://licensing.meteorite.bi. You can upload it at /upload.html");
	//	}

	//	if (sl != null) {

	//		try {
	//			l.validateLicense();
	//		} catch (RepositoryException | IOException | ClassNotFoundException e) {
	//			log.debug("Repository Exception, couldn't get license", e);
	//			throw new LicenseException("Error fetching license. Please check your logs.");
	//		}

        if (authenticationManager != null) {
            authenticate(req, username, password);
        }
        if (SecurityContextHolder.getContext() != null
            &amp;&amp; SecurityContextHolder.getContext().getAuthentication() != null) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();

            if (authorisationPredicate.isAuthorised(auth)) {
                Object p = auth.getPrincipal();
                createSession(auth, username, password);
                return sessionHolder.get(p);
            } else {
                log.info(username + " failed authorisation. Rejecting login");
                throw new RuntimeException("Authorisation failed for: " + username);
            }
        }
        return new HashMap&lt;&gt;();
	}
</code></pre>
<ol start="3">
 <li>saiku\saiku-ui\js\saiku\models\Session.js</li>
</ol>
<p>需要更改process_session和check_session方法</p>
<pre><code class="language-java">check_session: function() {
		// This authentication cookie is used only by Orbis authentication strategy
		var authCookie = this.getCookie(Settings.ORBIS_AUTH.cookieName);

		if (Settings.ORBIS_AUTH.hazelcast_enabled &amp;&amp; authCookie &amp;&amp; !this.atemptedToLoginByCookie) {
            this.sessionid               = 1;
            this.username                = authCookie;
            this.password                = authCookie;
            this.atemptedToLoginByCookie = true;

            // In this case we inject the proper license attributes
            var ONE_YEAR = 31556952000;
			/**
            Settings.LICENSE = {
              licenseType: 'Orbis',
              expiration: Date.now() + ONE_YEAR
            }
            */
            this.login(authCookie, authCookie);
		} else {
			if (this.sessionid === null || this.username === null || this.password === null) {
				var that = this;
				this.clear();
				this.fetch({ success: this.process_session, error: this.brute_force });
			} else {
                if (!this.atemptedToLoginByCookie) {
                    this.username = encodeURIComponent(options.username);
                }

				this.load_session();
			}
		}
    },

	process_session: function(model, response) {
        if ((response === null || response.sessionid == null)) {
            // Open form and retrieve credentials
            Saiku.ui.unblock();
            if (Settings.DEMO) {
                this.form = new DemoLoginForm({ session: this });
            } else {
                this.form = new LoginForm({ session: this });
            }
            this.form.render().open();
        } else {
            this.sessionid = response.sessionid;
            this.roles = response.roles;
            this.isAdmin = Settings.ORBIS_AUTH.hazelcast_enabled || response.isadmin;
            this.username = encodeURIComponent(response.username);
            this.language = response.language;
            if (typeof this.language != "undefined" &amp;&amp; this.language != Saiku.i18n.locale) {
                Saiku.i18n.locale = this.language;
                Saiku.i18n.automatic_i18n();
            }
			/**
                var license =new License();

                license.fetch_license('api/license/', function(opt) {
                    if (opt.status === 'success') {
                        Settings.LICENSE = opt.data.toJSON();
                    }
                    if(Saiku.session.isAdmin) {

                        var quota = new LicenseQuota();

                        quota.fetch_quota('api/license/quota', function (opt) {
                            if (opt.status === 'success') {
                                Settings.LICENSEQUOTA = opt.data.toJSON();
                            }
                        });
                    }

                });

			*/
            this.load_session();
        }

        return this;
    },
</code></pre>
<ol start="4">
 <li>saiku\saiku-ui\js\saiku\views\Upgrade.js</li>
</ol>
<p>去除升级提示，注释掉所有render的内容</p>
<pre><code class="language-java">render: function() {
		/*
		var self = this;
		var license = new License();

		if(Settings.BIPLUGIN5){
				if(Saiku.session.get("notice") != undefined &amp;&amp; Saiku.session.get("notice")!=null &amp;&amp; Saiku.session.get("notice")!=""){
					$(this.el).append("&lt;div&gt;&lt;div id='uphead' class='upgradeheader'&gt;Notice:"+Saiku.session.get("notice")+"&lt;/div&gt;");

				}
				if (Settings.LICENSE.licenseType != undefined &amp;&amp; (Settings.LICENSE.licenseType != "trial" &amp;&amp; Settings.LICENSE.licenseType != "Open Source License")) {
					return this;
				}
				if (Settings.LICENSE != undefined &amp;&amp; Settings.LICENSE.licenseType === "trial") {
					var yourEpoch = parseFloat(Settings.LICENSE.expiration);
					var yourDate = new Date(yourEpoch);
					self.remainingdays = self.daydiff(new Date(), yourDate);


					$(this.el).append("&lt;div&gt;&lt;div id='uphead' class='upgradeheader'&gt;You are using a Saiku Enterprise" +
						" Trial license, you have "+ self.remainingdays+" days remaining. &lt;a href='http://www.meteorite.bi/saiku-pricing'&gt;Buy licenses online.&lt;/a&gt;&lt;/div&gt;");
					return self;
				}
				else {
					$(this.el).append("&lt;div&gt;&lt;div id='uphead' class='upgradeheader'&gt;You are using Saiku Community" +
						" Edition, please consider upgrading to &lt;a target='_blank' href='http://meteorite.bi'&gt;Saiku Enterprise&lt;/a&gt;, or entering a &lt;a href='http://meteorite.bi/products/saiku/sponsorship'&gt;sponsorship agreement with us&lt;/a&gt; to support development. " +
						"&lt;a href='http://meteorite.bi/products/saiku/community'&gt;Or contribute by joining our community and helping other users!&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;");

					return self;
				}
		}
		else {
				if(Saiku.session.get("notice") != undefined &amp;&amp; Saiku.session.get("notice")!=null &amp;&amp; Saiku.session.get("notice")!=""){
					$(this.el).append("&lt;div&gt;&lt;div id='uphead' class='upgradeheader'&gt;Notice:"+Saiku.session.get("notice")+"&lt;/div&gt;");

				}
				if (Settings.LICENSE.licenseType != undefined &amp;&amp; (Settings.LICENSE.licenseType != "trial" &amp;&amp;
					Settings.LICENSE.licenseType != "Open Source License")) {
					return this;
				}
				if (Settings.LICENSE.licenseType === "trial") {
					var yourEpoch = parseFloat(Settings.LICENSE.expiration);
					var yourDate = new Date(yourEpoch);

					self.remainingdays = self.daydiff(new Date(), yourDate);

					$(this.el).append("&lt;div&gt;&lt;div id='uphead' class='upgradeheader'&gt;You are using a Saiku Enterprise" +
						" Trial license, you have "+ self.remainingdays+" days remaining. &lt;a href='http://www.meteorite.bi/saiku-pricing'&gt;Buy licenses online.&lt;/a&gt;&lt;/div&gt;");
					return self;
				}
				else {
					$(this.el).append("&lt;div&gt;&lt;div id='uphead' class='upgradeheader'&gt;You are using Saiku Community" +
						" Edition, please consider upgrading to &lt;a target='_blank' href='http://meteorite.bi'&gt;Saiku Enterprise&lt;/a&gt;, or entering a &lt;a href='http://meteorite.bi/products/saiku/sponsorship'&gt;sponsorship agreement with us&lt;/a&gt; to support development. " +
						"&lt;a href='http://meteorite.bi/products/saiku/community'&gt;Or contribute by joining our community and helping other users!&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;");
					return self;
				}
		}
		*/
	},
</code></pre>
<p>去除之后重新打包即可</p>
<h2 id="%E9%97%AE%E9%A2%98%E5%8F%8A%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88" tabindex="-1">问题及解决方案</h2>
<h3 id="%E4%B8%80%E3%80%81%E5%90%AF%E5%8A%A8%E6%8A%A5%E9%94%99-cannot-set-sax-feature-because-outdated-xml-parser-in-classpath%3A-http%3A%2F%2Fjavax.xml.xmlconstants%2Ffeature%2Fsecure-processing" tabindex="-1">一、启动报错&nbsp;Cannot set SAX feature because outdated XML parser in classpath: <a href="http://javax.xml.XMLConstants/feature/secure-processing" target="_blank">http://javax.xml.XMLConstants/feature/secure-processing</a></h3>
<h4 id="%E9%97%AE%E9%A2%98%E5%8E%9F%E5%9B%A0" tabindex="-1">问题原因</h4>
<p>Saiku 自带的xerces，与jdk8中的JAX-B不兼容</p>
<h4 id="%E8%A7%A3%E5%86%B3%E6%96%B9%E5%BC%8F" tabindex="-1">解决方式</h4>
<ol>
 <li>降级，从jdk1.8 降级到 jdk1.7</li>
 <li>为java添加系统变量。编辑 saiku\saiku-server\target\dist\saiku-server\start-saiku.bat，在CATALINA_OPTS 后面加上如下内容</li>
</ol>
<pre><code class="language-">-Dorg.xml.sax.parser="com.sun.org.apache.xerces.internal.parsers.SAXParser" -Djavax.xml.parsers.DocumentBuilderFactory="com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl" -Djavax.xml.parsers.SAXParserFactory="com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"
</code></pre>
<p>如果不想打包就更改的话，可以直接设置</p>
<pre><code class="language-java">System.setProperty("org.xml.sax.driver", "com.sun.org.apache.xerces.internal.parsers.SAXParser");
System.setProperty("javax.xml.parsers.DocumentBuilderFactory","com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
System.setProperty("javax.xml.parsers.SAXParserFactory","com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
</code></pre>
<p>或者在maven的tomcat插件里加上</p>
<pre><code class="language-xml">&lt;javax.xml.parsers.DocumentBuilderFactory&gt;com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl&lt;/javax.xml.parsers.DocumentBuilderFactory&gt;
&lt;org.xml.sax.parser&gt;com.sun.org.apache.xerces.internal.parsers.SAXParser&lt;/org.xml.sax.parser&gt;
&lt;javax.xml.parsers.SAXParserFactory&gt;com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl&lt;/javax.xml.parsers.SAXParserFactory&gt;
</code></pre>
<h4 id="%E5%8F%82%E8%80%83%E6%96%87%E7%8C%AE" tabindex="-1">参考文献</h4>
<p><a href="https://stackoverflow.com/questions/25644023/error-unmarshalling-xml-in-java-8-secure-processing-org-xml-sax-saxnotrecognize" target="_blank">Error unmarshalling xml in java-8 “secure-processing org.xml.sax.SAXNotRecognizedException causing java.lang.IllegalStateException”</a></p>]]></description><guid isPermaLink="false">/archives/saiku</guid><dc:creator>Takagi</dc:creator><category>Java</category><category>经验宝宝</category><pubDate>Thu, 18 Jun 2020 09:55:00 GMT</pubDate></item><item><title><![CDATA[ztree节点的渲染事件]]></title><link>https://lixingyong.com/archives/ztree</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=ztree%E8%8A%82%E7%82%B9%E7%9A%84%E6%B8%B2%E6%9F%93%E4%BA%8B%E4%BB%B6&amp;url=/archives/ztree" width="1" height="1" alt="" style="opacity:0;">
<p>ztree中没有专门的节点渲染回调事件，但可以根据view下的addDiyDom来达到相同的效果
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimgconvert.csdnimg.cn%2FaHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAyMC9wbmcvMTM4NzY3NC8xNTkwNjYyMTcwOTIwLWIzODNmZDU5LTBlYjktNGYzYi1iMTY1LTM0M2M4OGM0NjFlOC5wbmc%3Fx-oss-process%3Dimage%2Fformat%2Cpng&amp;size=m" alt="在这里插入图片描述"></p>
<h2 id="使用方式">使用方式</h2>
<pre><code class="language-javascript">let setting = {
  view: {
    addDiyDom: addDiyDom
  }
}

function addDiyDom(treeId, treeNode) {
	// 在这里通过获取dom节点来处理节点的特殊样式
}
</code></pre>]]></description><guid isPermaLink="false">/archives/ztree</guid><dc:creator>Takagi</dc:creator><pubDate>Mon, 8 Jun 2020 11:49:31 GMT</pubDate></item><item><title><![CDATA[Nginx防止DDos&&CC攻击]]></title><link>https://lixingyong.com/archives/nginx-ddos-cc</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=Nginx%E9%98%B2%E6%AD%A2DDos%26%26CC%E6%94%BB%E5%87%BB&amp;url=/archives/nginx-ddos-cc" width="1" height="1" alt="" style="opacity:0;">
<h2 id="限制每个ip每秒的连接数">限制每个IP每秒的连接数</h2>
<pre><code class="language-nginx">http {
  # 用户ip每秒的连接数
  limit_conn_zone $binary_remote_addr zone=peripconn:1m;
  # 虚拟主机每秒的连接数
  limit_conn_zone $server_name zone=perserverconn:1m;
  
  server {
    limit_conn peripconn 5;
    limit_conn perserverconn 50;
  }
}
</code></pre>
<h2 id="限制每个ip每秒的请求数">限制每个IP每秒的请求数</h2>
<pre><code class="language-nginx">http {
  # ip每秒请求数
  limit_req_zone $binary_remote_addr zone=peripreq:1m rate=5r/s;
  # 虚拟服务器每秒请求数
  limit_req_zone $server_name zone=perserverreq:1m rate=10r/s;
  
  server {
    # burst为突发请求，最大突发请求为5个 nodelay 即为立即返回503 不缓存
    limit_req zone=peripreq burst=5 nodelay;
    limit_req zone=perserverreq burst=10;
  }
}
</code></pre>
<h2 id="后注">后注</h2>
<p>经过实际测试，一般的个人用机使用用当前方法阻止DDos和CC攻击的效果有是有，但不是很明显。毕竟服务器光处理垃圾请求就已经满负荷运行了，虽然服务器不至于很容易崩溃，但却会导致超时响应。
 <br>
 <strong>个人更加推荐上述方式配合使用cdn实现，一来能隐藏网站ip，二来还能加速网站，一举多得</strong></p>
<h2 id="参考链接">参考链接</h2>
<p><a href="https://segmentfault.com/q/1010000000115949">如何在nginx上防止恶意的ddos抓取</a></p>]]></description><guid isPermaLink="false">/archives/nginx-ddos-cc</guid><dc:creator>Takagi</dc:creator><category>文章</category><pubDate>Mon, 8 Jun 2020 11:48:57 GMT</pubDate></item><item><title><![CDATA[MySql 重置/修改表自增ID值]]></title><link>https://lixingyong.com/archives/mysql</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=MySql%20%E9%87%8D%E7%BD%AE%2F%E4%BF%AE%E6%94%B9%E8%A1%A8%E8%87%AA%E5%A2%9EID%E5%80%BC&amp;url=/archives/mysql" width="1" height="1" alt="" style="opacity:0;">
<h4 id="第一种方案使用truncate命令">第一种方案，使用truncate命令</h4>
<pre><code class="language-plsql">truncate table table_name
</code></pre>
<p>该方式会<strong>清空表</strong>并恢复索引至初始值</p>
<h4 id="第二种方案-使用alter命令">第二种方案 使用alter命令</h4>
<pre><code class="language-plsql">alter table table_name AUTO_INCREMENT=1
</code></pre>
<p>将设置自增值为后面的数【但不可以小于当前值】</p>
<h4 id="第三种方案使用工具例如navicat">第三种方案，使用工具，例如Navicat</h4>
<p>如下图所示，点击设计表，将自动递增改成想要的即可<img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimgconvert.csdnimg.cn%2FaHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAyMC9wbmcvMTM4NzY3NC8xNTg5NjA5NDc2MDM3LTRlMzM5NWIzLTE4MjMtNDUzYi1iOGI0LWI1Zjc5MTc5NmJhYy5wbmc%3Fx-oss-process%3Dimage%2Fformat%2Cpng%23pic_center&amp;size=m" alt="在这里插入图片描述">
 <br>
 该方式与第二种方式同理</p>]]></description><guid isPermaLink="false">/archives/mysql</guid><dc:creator>Takagi</dc:creator><category>文章</category><pubDate>Mon, 8 Jun 2020 11:47:24 GMT</pubDate></item><item><title><![CDATA[Quartz 注入 Spring Bean为空]]></title><link>https://lixingyong.com/archives/quartz</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=Quartz%20%E6%B3%A8%E5%85%A5%20Spring%20Bean%E4%B8%BA%E7%A9%BA&amp;url=/archives/quartz" width="1" height="1" alt="" style="opacity:0;">
<h3 id="问题描述">问题描述</h3>
<p>项目中采用了Quartz来执行调度任务，但在 Quartz自动调用 Job任务时，发现在JobBean中使用@Autowired进行依赖注入会产生null指针错误
 <br>
 经查阅资料得知，大致原因为Job由Quartz实例化创建，因而在Job中使用依赖注入时无法找到Spring的Bean
 <br>
 开发所使用的版本号</p>
<blockquote>
 <p>SpringBoot：2.1.5.RELEASE
  <br>
  quartz：2.3.0</p>
</blockquote>
<h3 id="解决方案">解决方案</h3>
<p>经过我的研究，无论是好坏的方法共有下面几种，都已经过测试。【这里我推荐第一种，更加符合Spring的要求】</p>
<h4 id="一使用springbeanjobfactory将job对象与spring对象关联">一、使用SpringBeanJobFactory，将Job对象与Spring对象关联</h4>
<p>先创建一个Factory，该方法继承<strong>SpringBeanJobFactory</strong>并实现<strong>ApplicationContextAware</strong>
 <br>
 通过<strong>autowireBean</strong>方法将Quartz实例化后的Job添加到Spring的Bean中</p>
<pre><code class="language-java">public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
        ApplicationContextAware {
    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        beanFactory = context.getAutowireCapableBeanFactory();
    }
	
    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job;
    }
}

</code></pre>
<p>然后，将其附加到ScheduleConfig</p>
<pre><code class="language-java"> 	@Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(SpringContextUtils.applicationContext);
        factory.setJobFactory(jobFactory);
        
        ...........
    }
</code></pre>
<p>其中SpringContextUtils为自定义的Spring Context 工具类</p>
<pre><code class="language-java">@Component
public class SpringContextUtils implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }
}
</code></pre>
<p>推荐优先使用该方式</p>
<hr>
<h4 id="二在servlet中调用springbeanautowiringsupport">二、在Servlet中调用SpringBeanAutowiringSupport</h4>
<p>使用当前方法需要Spring-Web版本大于 2.5.1
 <br>
 将其作为Job的第一行即可</p>
<pre><code class="language-java">public class BatchJob extends Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        
        ...........
    }
}
</code></pre>
<p>该方式虽可行，但不利于多个Job的情况</p>
<hr>
<h4 id="三直接使用工具类获取bean">三、直接使用工具类获取Bean</h4>
<p>改造第一种方法中的工具类如下，增加获取bean的方法</p>
<pre><code class="language-java">@Component
public class SpringContextUtils implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取Bean
     * @param name bean名称
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }
}
</code></pre>
<p>之后在需要使用Bean的地方直接使用工具类获取。例如</p>
<pre><code class="language-java">public class BatchJob extends Job {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        // 需要获取的Bean
        JobService jobService = (JobService) SpringContextUtils.getBean("jobService");
        ...........
    }
}
</code></pre>
<p>当前方式简单但与第二个方法大同小异，都不利于多种任务的情况</p>
<h3 id="总结">总结</h3>
<p>严格来说还有其他的方式，比如继承QuartzJobBean，但实际验证后并无作用，因此目前就列举以上三种，各有优缺点，可根据需求自行选择。
 <br>
 另外作者才疏学浅，若有疏漏或不对的地方敬请谅解！
 <br>
 转载请注明出处！！！</p>
<h3 id="参考">参考</h3>
<p><a href="https://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring#">stackoverflow</a>
 <br>
 <a href="https://www.iteye.com/blog/angelbill3-2371756">SpringBeanAutowiringSupport介绍</a></p>]]></description><guid isPermaLink="false">/archives/quartz</guid><dc:creator>Takagi</dc:creator><category>文章</category><pubDate>Mon, 8 Jun 2020 11:46:43 GMT</pubDate></item><item><title><![CDATA[JQuery获取元素的唯一选择器]]></title><link>https://lixingyong.com/archives/jquery-dom-select</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=JQuery%E8%8E%B7%E5%8F%96%E5%85%83%E7%B4%A0%E7%9A%84%E5%94%AF%E4%B8%80%E9%80%89%E6%8B%A9%E5%99%A8&amp;url=/archives/jquery-dom-select" width="1" height="1" alt="" style="opacity:0;">
<p>项目中需要单击某个元素之后，获取当前元素的唯一选择器，使用下面的方法来获取。</p>
<p>添加Jquery原型</p>
<pre><code class="language-javascript">/**
* 添加查询路径方法到jquery原型链
*/
jQuery.fn.extend({
    getPath: function () {
        var path, node = this;
        while (node.length) {
            var realNode = node[0], name = realNode.localName;
            if (!name) break;
            name = name.toLowerCase();
            var parent = node.parent();
            var sameTagSiblings = parent.children(name);
            if (sameTagSiblings.length &gt; 1) { 
                let allSiblings = parent.children();
                var index = allSiblings.index(realNode) + 1;
                if (index &gt; 0) {
                    name += ':nth-child(' + index + ')';
                }
            }
            path = name + (path ? '&gt;' + path : '');
            node = parent;
        }
        return path;
    }
});
</code></pre>
<p>使用方法</p>
<pre><code class="language-javascript">$(e.target).getPath()
</code></pre>
<p>参考资料
 <br>
 <a href="https://www.javascriptcn.com/read-24456.html">在jQuery中获取元素的唯一选择器</a></p>]]></description><guid isPermaLink="false">/archives/jquery-dom-select</guid><dc:creator>Takagi</dc:creator><category>文章</category><pubDate>Mon, 8 Jun 2020 11:45:37 GMT</pubDate></item><item><title><![CDATA[在Vue中使用NProgress监控页面滚动进度]]></title><link>https://lixingyong.com/archives/nprogress</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=%E5%9C%A8Vue%E4%B8%AD%E4%BD%BF%E7%94%A8NProgress%E7%9B%91%E6%8E%A7%E9%A1%B5%E9%9D%A2%E6%BB%9A%E5%8A%A8%E8%BF%9B%E5%BA%A6&amp;url=/archives/nprogress" width="1" height="1" alt="" style="opacity:0;">
<blockquote>
 <p><a href="http://ricostacruz.com/nprogress/">NProgress</a>是用来在页面跳转时出现在浏览器顶部的进度条
  <br>
  官网：<a href="http://ricostacruz.com/nprogress/">http://ricostacruz.com/nprogress/</a>
  <br>
  github: <a href="https://github.com/rstacruz/nprogress">https://github.com/rstacruz/nprogress</a></p>
</blockquote>
<p>博主想用Vue实现全局监控页面滚动条的进度。功能与NProgress相似，因此直接使用当前插件来进行实现。</p>
<p><strong>效果：</strong>
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190923162318142.gif&amp;size=m" alt="在这里插入图片描述"></p>
<h3 id="一安装">一、安装</h3>
<blockquote>
 <p>npm install --save nprogress
  <br>
  或
  <br>
  yarn add nprogress</p>
</blockquote>
<h3 id="二使用">二、使用</h3>
<h5 id="1-作为加载进度条">1. 作为加载进度条</h5>
<p>在Vue入口文件 main.js 中引入 nprogress</p>
<pre><code class="language-js">import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' //引入 nprogress 插件
import 'nprogress/nprogress.css' // 引入基础样式
</code></pre>
<p>切换路由时进行加载（也是在main.js中）</p>
<pre><code class="language-javascript">//当路由进入前
router.beforeEach((to, from, next) =&gt; {
  // 每次切换页面时，调用进度条
  NProgress.start();
  // 这个一定要加，没有next()页面不会跳转的。这部分还不清楚的去翻一下官网就明白了
  next();
});
//当路由进入后：关闭进度条
router.afterEach(() =&gt; {
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done()
})
</code></pre>
<h4 id="2-作为页面滚动进度条">2. 作为页面滚动进度条</h4>
<p>在 App.vue 中</p>
<pre><code class="language-js">&lt;script&gt;
import NProgress from "nprogress"; // 导入nprogress（因为在main.js 中已经导入样式，这里不需要再次导入）
export default {
  name: "App",
  mounted() {
    window.addEventListener("scroll", this.handleScroll); // 监听滚动条事件
  },
  methods: {
    handleScroll() {
      // 屏幕剩余的高度
      let surplus =
        document.documentElement.scrollHeight -
        document.documentElement.clientHeight;
      // 当前滑动高度
      let scrollY = document.documentElement.scrollTop;
      // 当前位置百分比小数
      let coorY = scrollY / surplus;
      // 设置导航栏，这里使用NProgress.set() 动态更改进度条
     NProgress.set(coorY);
    }
  }
};
&lt;/script&gt;
</code></pre>
<hr>
<h3 id="三配置项">三、配置项</h3>
<h5 id="1-更改默认样式">1. 更改默认样式：</h5>
<p>在 App.vue 中</p>
<pre><code class="language-css">&lt;style&gt;
#nprogress .bar{ //自定义进度条颜色
  background: orange !important; 
}
#nprogress .peg { // 自定义辅助阴影颜色，这里默认为透明
  box-shadow: 0 0 10px #00000000, 0 0 5px #00000000 !important; 
}
&lt;/style&gt;
</code></pre>
<h5 id="2-配置nprogress">2. 配置NProgress：</h5>
<ol>
 <li>showSpinner：进度环显示隐藏</li>
</ol>
<pre><code class="language-js">NProgress.configure({showSpinner: false});
</code></pre>
<ol start="2">
 <li>ease：调整动画设置，ease可传递CSS3缓冲动画字符串（如ease、linear、ease-in、ease-out、ease-in-out、cubic-bezier）。speed为动画速度（单位ms）</li>
</ol>
<pre><code class="language-js">NProgress.configure({ease:'ease',speed:1000});
</code></pre>
<ol start="3">
 <li>minimum：设置进度条最低百分比</li>
</ol>
<pre><code class="language-js">NProgress.configure({minimum:0.0});
</code></pre>
<ol start="4">
 <li>百分比：通过设置progress的百分比，调用 .set(n)来控制进度，其中n的取值范围为0-1</li>
</ol>
<pre><code class="language-js">NProgress.set(0.4);
</code></pre>
<h4 id="四参考文献">四、参考文献</h4>
<blockquote>
 <p><a href="https://www.jianshu.com/p/346c05d4d9d8">在Vue使用NProgress加载进度条</a>
  <br>
  <a href="https://github.com/rstacruz/nprogress">NProgress - github</a>
  <br>
  <a href="https://www.cnblogs.com/yck123/p/10978941.html">vue滚动条事件（获取滚动条距离底部距离）</a></p>
</blockquote>]]></description><guid isPermaLink="false">/archives/nprogress</guid><dc:creator>Takagi</dc:creator><category>文章</category><pubDate>Mon, 8 Jun 2020 11:44:41 GMT</pubDate></item><item><title><![CDATA[使用echarts实现系统性能动态监控（数据实时展示）]]></title><link>https://lixingyong.com/archives/echarts-monitor</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=%E4%BD%BF%E7%94%A8echarts%E5%AE%9E%E7%8E%B0%E7%B3%BB%E7%BB%9F%E6%80%A7%E8%83%BD%E5%8A%A8%E6%80%81%E7%9B%91%E6%8E%A7%EF%BC%88%E6%95%B0%E6%8D%AE%E5%AE%9E%E6%97%B6%E5%B1%95%E7%A4%BA%EF%BC%89&amp;url=/archives/echarts-monitor" width="1" height="1" alt="" style="opacity:0;">
<h4 id="一-实现效果">一、 实现效果</h4>
<p>先来一张效果图.gif
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190920133008897.gif&amp;size=m" alt="在这里插入图片描述"></p>
<h4 id="二解决方案">二、解决方案</h4>
<p><strong>1、目前的解决方案（异步加载）</strong></p>
<p>目前的实现方式比较简单，前端定时从后台请求数据并渲染Echarts，这样做的方式比较简单粗暴，但也有如下几个问题：</p>
<p>a、前端定时从服务器获取数据，会对服务器造成巨大的压力，尤其是监控数据分为多个不同请求的情况下。
 <br>
 b、大量的并发请求，势必会阻塞服务器请求，导致响应缓慢甚至服务器瘫痪。</p>
<p>进而看出目前的方案并不是很好的，但他简单啊<sup>-</sup></p>
<p><strong>2、稍作改进方案</strong></p>
<p>下一步方案实际上是另一个员工提出来的，但其实并不叫改进，只能叫做妥协，就是后台定时获取监控数据并保存在redis中。之后前端写一个请求按钮，每次点击请求时，再从redis中获取数据，这样做的优点很多，有下面几种：</p>
<p>a、对服务器的压力大量减少，前端最少一次请求即可展现页面。
 <br>
 b、后台服务器定时获取数据，在固定的时间段只有有限的请求次数，不用担心服务器性能问题。</p>
<p>但缺点也很明显，那就是不能动态刷新数据了，必须手动进行刷新。</p>
<p><strong>3、更好的解决方案</strong></p>
<p>更好的方案可以使用长连接进行，前台轮询请求，后台如果有数据的更新则向前端返回新的数据，重新进行渲染。
 <br>
 尽管第三种方式更符合，但也需要进行一定的改动，因此我这里采用最简单的第一种。下一个版本可能会采用第二种，毕竟客户的要求不一样，也不一定非要动态更新图表。</p>
<p>接下来一步一步来实现效果图中的样式</p>
<h4 id="三前端代码实现">三、前端代码实现</h4>
<p>作为一个非专业的前端小白，目前就是能有效果就行，因此代码写的可能比较凌乱。
 <br>
 由于前端采用的是webpack，而Echarts官方从3.1.1开始维护NPM上的package了，因此直接查看Echarts官网进行安装即可。</p>
<blockquote>
 <p><strong>在webpack中使用ECharts</strong>：<a href="https://www.echartsjs.com/zh/tutorial.html#%E5%9C%A8%20webpack%20%E4%B8%AD%E4%BD%BF%E7%94%A8%20ECharts">https://www.echartsjs.com/zh/tutorial.html#%E5%9C%A8%20webpack%20%E4%B8%AD%E4%BD%BF%E7%94%A8%20ECharts</a></p>
</blockquote>
<p>本项目中还使用到了echarts的 liquidfill（水球）插件。
 <br>
 liquidfill: <a href="https://github.com/ecomfe/echarts-liquidfill#api">https://github.com/ecomfe/echarts-liquidfill#api</a></p>
<p>使用下列命令导入</p>
<blockquote>
 <p>npm install echarts-liquidfill --save</p>
</blockquote>
<p>a、按照教程导入需要的模块（按需导入）</p>
<pre><code class="language-javascript">/**
    index.js
*/
// 引入 ECharts 主模块
let echarts = require('echarts/lib/echarts');
// 引入饼图
require('echarts/lib/chart/pie');
// 引入折线图
require('echarts/lib/chart/line');
// 引入柱状图
require('echarts/lib/chart/bar');
// 引入雷达图
require('echarts/lib/chart/radar');
// 引入水球
require('echarts-liquidfill') // 水球需要单独安装
// 引入提示框和标题组件
require('echarts/lib/component/tooltip');
require('echarts/lib/component/title');
// 引入图例组件
require('echarts/lib/component/legend');
</code></pre>
<p>b、统一初始化所有图表，这一部分只是初始化，使Echarts图表绑定在dom上，绑定上的dom都会有一个loading的动画。不做其他处理。</p>
<pre><code class="language-javascript">/**
    index.js
*/
/** 统一加载所有的echarts */
let initEcharts = () =&gt; {
    $('.echart').each((index, dom) =&gt; {
        if($(dom).attr("id") != "jvm_gc"){ //排除最后一个文字域的加载动画
            echarts.init(dom).showLoading();  //  初始化所有dom并显示加载动画
        }
    })
    // 设置每个图表的不同初始化样式
    echartsSetInitOption();
    // 定时刷新
    window.setInterval(function() {
        getMonData()； //这里用来获取数据
    },5000)
}
</code></pre>
<p>c、进行每个图表的个性化定制（代码太多，这里只列出一个），图表采用异步加载，因此，这部分处理所有图表的基础样式，也不进行数据填充。整个界面展示阶段这里只加载一次。</p>
<pre><code class="language-javascript">/**
    index.js
*/
/**
 * 初始化所有图表样式（这部分只是公共样式设置，还不会填充任何数据）
 */
let echartsSetInitOption = () =&gt; {
    // 饼图的公共系列属性
    let pieSeries = {
        type: 'pie',
        radius: ['50%', '55%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        hoverAnimation: false,
        silent: true,
        itemStyle: {
            normal: {
                color: '#F76A4F'
            }
        },
        label: {
            normal: {
                show: true,
                position: 'center',
                formatter: function (params) {
                    return '{value|' + params.value + '} {unit|%}\n{name|' + params.name + '}';
                },
                rich: {
                    value: {
                        fontFamily: 'SFUDINEngschrift',
                        fontSize: 24,
                        fontWeight: 200,
                        color: '#343434',
                        verticalAlign: 'bottom'
                    },
                    unit: {
                        fontFamily: 'SFUDINEngschrift',
                        fontSize: 11,
                        color: '#9F9F9F',
                        lineHeight: 17,
                        verticalAlign: 'bottom'
                    },
                    name: {
                        fontFamily: 'Microsoft YaHei',
                        fontSize: 11,
                        color: '#9F9F9F',
                        lineHeight: 20,
                    }
                }
            },
        },
    };
    // 基础标题（左上角那个）
    let baseTitle = {
        top: '5%',
        left: '5%',
        textStyle: {
            color: '#A5A9B2',
            fontWeight: 600,
            fontSize: 12
        }
    }
    // 公共配置
    let pieBaseOption = {
        title: baseTitle,
        series: [pieSeries]
    };
    
    //CPU使用率的默认样式
    let data = [];
    pieBaseOption.title.text = "CPU 使用率";
    pieSeries.name = "cpu_usage_rate";
    // CPU使用率
    echarts.getInstanceByDom($("#cpu_usage_rate")[0]).setOption(pieBaseOption);
    
     // 初始化结束之后，开始获取服务器数据
    getMonData();
</code></pre>
<p>d、获取服务器数据并准备绑定数据到echarts。由于不同监控数据在不同的请求接口，因此这里要等所有的数据都加载完毕再进行渲染（一个数据可能会使用到另一个）</p>
<pre><code class="language-javascript">/**
    index.js
*/
// 获取服务器数据，并将其封装为echarts数据
let getMonData = () =&gt; {
    // 确保所有数据请求完毕后才进行渲染
    Promise.all([serviceMonData(), tomcatMonData(), jvmMonData(), traceMonData()]).then(function (r) {
        // 获取到数据之后必定触发数据处理，用来适配Echarts
        echartsDataAdapter();
    })
}
let serviceMonData = () =&gt; {
    return ajax.get('/sys/actuate/service/list').then(function (r) {
        serviceData = r.list
    })
}
let tomcatMonData = () =&gt; {
    return ajax.get('/sys/actuate/tomcat/list').then(function (r) {
        tomcatData = r.list;
    })
}
let jvmMonData = () =&gt; {
    return ajax.get('/sys/actuate/jvm/list').then(function (r) {
        jvmData = r.list;
    })
}
let traceMonData = () =&gt; {
    return ajax.get('/sys/actuate/httpTrace/list').then(function(r){
        traceData = r.page.list;
    })
}
</code></pre>
<p>e、绑定数据到Echarts中。这部分也需要进行数据的适配，需要将请求获取到的数据做一定的处理绑定到echarts上。</p>
<pre><code class="language-javascript">/**
    index.js
*/
/**
 * 获取到的数据适配Echarts
 */
let echartsDataAdapter = () =&gt; {
    let data = [];
    let realtimeData = [];
    if (serviceData) {
        serviceData.forEach((item, index) =&gt; {
            // CPU使用率
            if (item.name == "system.cpu.usage") {
                data = [
                    { value: 0, name: 'CPU占用率' },
                    {
                        value: 0,
                        name: 'invisible',
                        label: {
                            show: false
                        },
                        itemStyle: {
                            normal: {
                                color: '#E6E6E6',
                            }
                        }
                    }
                ];
                data[0].value = Math.round(item.measurements[0].value * 100);
                data[1].value = 100 - Math.round(item.measurements[0].value * 100);
                // 将data赋值
                let echartsInstance = echarts.getInstanceByDom($("#cpu_usage_rate")[0]);
                echartsInstance.setOption({
                    series: [{
                        data: data
                    }]
                });
                echartsInstance.hideLoading(); // 去除loading
            }
        })
    }
}
</code></pre>
<h4 id="四数据格式">四、数据格式</h4>
<p>后台采用Actuator进行系统的监控管理。前台请求之后，便使用Actuator查询数据整理之后返回一个JSON文件格式。
 <br>
 由于项目采用前后端分离，后台代码的实现会单独开一篇文章来讲解，所以这里只介绍数据格式。</p>
<pre><code class="language-json">{   
    "msg":"success",   
    "code":0,    
    "list":[
        {
            "name":"process.cpu.usage",
            "description":"当前应用 CPU 使用率",
            "baseUnit":"",
            "patterValue":"0.34%",
            "group":"2",
            "measurements":[
                {
                    "statistic":"VALUE",
                    "value":0.003432716310723461
                }
            ],
            "availableTags":[
            ]
        },
        {
            "name":"process.start.time",
            "description":"应用启动时间点",
            "baseUnit":"",
            "patterValue":"2019-09-20 08:51:08",
            "group":"2",
            "measurements":[
                {
                    "statistic":"VALUE",
                    "value":1568940668.409
                }
            ],
            "availableTags":[
            ]
        },
        {
            "name":"process.uptime",
            "description":"应用已运行时间",
            "baseUnit":" 秒",
            "patterValue":"16079.006 秒",
            "group":"2",
            "measurements":[
                {
                    "statistic":"VALUE",
                    "value":16079.006
                }
            ],
            "availableTags":[
            ]
        },
        {
            "name":"system.cpu.count",
            "description":"CPU 数量",
            "baseUnit":" 核",
            "patterValue":"12 核",
            "group":"1",
            "measurements":[
                {
                    "statistic":"VALUE",
                    "value":12
                }
            ],
            "availableTags":[
            ]
        },
        {
            "name":"system.cpu.usage",
            "description":"系统 CPU 使用率",
            "baseUnit":"",
            "patterValue":"58.47%",
            "group":"1",
            "measurements":[
                {
                    "statistic":"VALUE",
                    "value":0.5847066456213992
                }
            ],
            "availableTags":[
            ]
        },
        {
            "name":"system.memory.usage",
            "description":"系统 内存 使用率",
            "baseUnit":null,
            "patterValue":"65.33%",
            "group":null,
            "measurements":[
                {
                    "statistic":null,
                    "value":0.6533496101899664
                }
            ],
            "availableTags":null
        }
    ]}
</code></pre>
<h4 id="五总结">五、总结</h4>
<p>按照目前的需求来看，当前的实现方式完全是可行的，但是会对服务器造成大量压力，第二版必定要处理这个问题。</p>
<h4 id="六参考资料">六、参考资料</h4>
<p>echarts官网：<a href="https://www.echartsjs.com/zh/index.html">https://www.echartsjs.com/zh/index.html</a></p>]]></description><guid isPermaLink="false">/archives/echarts-monitor</guid><dc:creator>Takagi</dc:creator><category>文章</category><pubDate>Mon, 8 Jun 2020 11:43:51 GMT</pubDate></item><item><title><![CDATA[使用Vue实现文本自动完成(快捷回复)]]></title><link>https://lixingyong.com/archives/vue-autocompletion</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=%E4%BD%BF%E7%94%A8Vue%E5%AE%9E%E7%8E%B0%E6%96%87%E6%9C%AC%E8%87%AA%E5%8A%A8%E5%AE%8C%E6%88%90%28%E5%BF%AB%E6%8D%B7%E5%9B%9E%E5%A4%8D%29&amp;url=/archives/vue-autocompletion" width="1" height="1" alt="" style="opacity:0;">
<p>2019/8/6</p>
<hr>
<h3 id="问题描述">问题描述</h3>
<hr>
<h5 id="简单描述">简单描述</h5>
<p>今天做了一个需求，就是使用<strong>textarea</strong>进行文本输入时，需要<strong>去后台请求字典项</strong>来自动完成一些预留的统一本文。刚开始感觉还蛮容易的，但是做到后面坑越来越大，因此记录一下详细的过程。（一个菜鸡后端程序猿，被逼着写前端，巨难受）</p>
<h5 id="需要注意的点">需要注意的点</h5>
<ol>
 <li>由于业务需要，前端的textarea对应的数据是一个数组，即<strong>textarea有多项</strong>。【如果是只有一个对象的话会很容易】</li>
 <li>前端监听字段变化有很多种办法，比如使用watch监听数组变化、computer计算属性、监听键盘事件，甚至使用jquery来监听焦点及文本变化等等。</li>
 <li>需要自动完成提示框能够根据当前文本所在位置来进行显示，类似于QQ的@功能及各种输入法的功能。</li>
 <li>可以考虑使用键盘上下键来进行选择，按回车键选择自动回复的内容，这样可以很大程度的方便用户。</li>
</ol>
<h5 id="成品展示">成品展示</h5>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F201908071931101.gif&amp;size=m" alt="在这里插入图片描述"></p>
<h5 id="参考文献">参考文献</h5>
<p><a href="https://ask.csdn.net/questions/679906">如何实现textarea中输入@在当前文本的右下方出现一个div，里面选择人名</a></p>
<h3 id="问题构思">问题构思</h3>
<hr>
<ul>
 <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" checked disabled readonly>&nbsp;<strong>为textarea设置文本变化监听事件，并获取到当前textarea的数组下标。</strong></li>
 <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled readonly>&nbsp;<del>在数据库中新增自动回复的数据，使用like 'xxx%'进行匹配。（业务需求，只考虑开头匹配，中间文本不支持）。</del></li>
 <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" checked disabled readonly>&nbsp;根据输入的文本，向后台请求自动完成字段。（由于有多个，因此返回值为一个List数组）</li>
 <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" checked disabled readonly>&nbsp;将请求到的数组，使用v-for渲染在需要展示的ul组件上。</li>
 <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled readonly>&nbsp;<strong>获取当前textarea中光标所在的位置，便于对齐ul组件</strong></li>
 <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled readonly>&nbsp;根据选中的li，将textarea对应数组的内容替换成当前选中li的文本。
  <br>
  <em>扩展选项</em></li>
 <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled readonly>&nbsp;<strong>监听键盘上下键，使得按上下键可以上下选择自动回复的文本。</strong></li>
 <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled readonly>&nbsp;<strong>监听键盘回车键，按下回车也可以达到和点击li一样的效果。</strong></li>
</ul>
<p>【粗体标注的是本文的重点内容，删除线不在本文的介绍范围内】</p>
<h3 id="解决方案及步骤">解决方案及步骤</h3>
<hr>
<h4 id="监听textarea文本变化">监听textarea文本变化</h4>
<p>由于业务需要，要获取到当前输入的文本值， textarea对应的数组下标以及触发当前文本变化的DOM。 因此，watch和computer方法不太适用（也可能是我没使用好，但他们两都获取不到数组下标以及DOM）。最终我采用了<strong>监听键盘事件</strong>的方法。尽管功能实现了，但仍旧感觉有所欠缺。。。
 <br>
 使用vue监听textarea键盘事件代码如下：</p>
<pre><code class="language-html">&lt;textarea style="margin-top: 10px" class="layui-textarea" v-for="(it, dex) in newApprove" :value="it" 
v-model="newApprove[dex]" @keyup="autoCompletion(it, dex, $event)"&gt;&lt;/textarea&gt;
</code></pre>
<p>其中newApprove为一个字符串数组：newApprove: [""],
 <br>
 autoCompletion用于监听文本的变化。方法第一个参数为当前文本、第二个为数组下标，第三个为事件。</p>
<p>atuoCompletion方法如下：</p>
<pre><code class="language-javascript">autoCompletion: function (text, index, e) {
    // 监听上键与下键，拦截默认事件并阻止冒泡
    if(e.keyCode === 38 || e.keyCode === 40) { 
        e.stopPropagation();
        e.preventDefault();
        return false; 
    }   
    var list = $("#list");
    // 键盘变化时，隐藏ul
    list.hide();
    clearTimeout(this.timer);  //清除延迟执行
     //设置延迟500毫秒执行
    this.timer = setTimeout(()=&gt;{
        // 保存当前数组下标
        vm.newApproveIndex = index;
        if(text.length &gt; 0) {
            // 请求快捷回复内容, 使用回调来处理成功返回的数据
            getAutoCompletionData(text, function (list) {
                //后端返回的数据，数据类型为List
                vm.autoCompletionData = list;
                // 触发显示选项框事件， 并绑定单击事件
                showAutoUI(text, e);
            });
        }
    }, 500);
},
</code></pre>
<h4 id="渲染获取到的数据">渲染获取到的数据</h4>
<p>下面的html是当前业务用到的所有html，其中<a href="https://www.layui.com/">layui</a>是一个前端开源框架，有需要的可以百度下载，不需要的删除即可。</p>
<pre><code class="language-html">&lt;!-- 这里是一个大的div --&gt;
&lt;div class="layui-field-box box"&gt;
    &lt;textarea style="margin-top: 10px" class="layui-textarea" v-for="(it, dex) in newApprove" :value="it" 
v-model="newApprove[dex]" @keyup="autoCompletion(it, dex, $event)"&gt;&lt;/textarea&gt;
    &lt;!-- 使用ul-li渲染获取到的自动回复内容 --&gt;
    &lt;ul id="list" &gt;
        &lt;li id="list_li" v-for="(item, index) in autoCompletionData" :tabindex=index 
@click="selectedAutoState(item.optName)"&gt;{{item.optName}}                 &lt;/li&gt;    
    &lt;/ul&gt; 
    &lt;!-- 用于点击事件，每点击一次增加一个textarea --&gt;
    &lt;div style="text-align: right;"&gt;
        &lt;i v-if="data.xmlJson.isManyApproval" class="layui-icon layui-icon-add-circle" style="font-size: 30px; color: 
#1E9FFF;" @click="addApproveDetail()"&gt;&lt;/i&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<h4 id="获取当前光标位置">获取当前光标位置</h4>
<p>获取光标位置需要在监听文本事件，即在<em>showAutoUI(text, e);</em> 方法内部。
 <br>
 以下是showAutoUI方法的代码。第一个参数为变化之后的文本，第二个为当前的点击事件。</p>
<pre><code class="language-javascript">function showAutoUI(text, e) {
    var curTarget = e.target;
    var list = $("#list");
    // 获取当前光标所处位置    
    var position = getPosition(curTarget);   
    // 光标处于文本最后    
    if(position === text.length){
        // 获取当前DOM的所有style
        var iStyle = window.getComputedStyle(curTarget);        
        //把双字节的替换成两个单字节的然后再获得长度        
        var len = (text || '').replace(/[^\x00-\xff]/g,"01").length / 2;        
        var fz = parseFloat(iStyle.fontSize);        
        var wd = parseFloat(iStyle.width);        
        var lh = parseFloat(iStyle.lineHeight);        
        list.css("left", fz * ( len % wd) &gt; wd ? wd : fz * (len % wd) + curTarget.offsetLeft + 5 + "px");        
        list.css("top", Math.ceil(len / wd) * lh +  curTarget.offsetTop + 5 +"px");
        list.find("li,.select").each(function({ 
            $(this).removeClass("select")        
        });
        list.show();
    }
}
</code></pre>
<p>getPosition即获取光标方法，其中参数为使当前文本改动的DOM，即textarea中拥有光标的那一个。getPosition方法代码如下：</p>
<pre><code class="language-javascript">//输入框获取光标
function getPosition(element) {    
    var cursorPos = 0;    
    if (document.selection) {//IE        
        var selectRange = document.selection.createRange();                    selectRange.moveStart('character', -element.value.length);
        cursorPos = selectRange.text.length;
    } else if (element.selectionStart || element.selectionStart == '0'{       
        cursorPos = element.selectionStart;   
    }    
    return cursorPos;
}
</code></pre>
<p>未完待续~</p>]]></description><guid isPermaLink="false">/archives/vue-autocompletion</guid><dc:creator>Takagi</dc:creator><category>文章</category><pubDate>Mon, 8 Jun 2020 11:41:25 GMT</pubDate></item><item><title><![CDATA[Vue安装（基于vue-cli 3.x可视化安装）]]></title><link>https://lixingyong.com/archives/vue-install</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=Vue%E5%AE%89%E8%A3%85%EF%BC%88%E5%9F%BA%E4%BA%8Evue-cli%203.x%E5%8F%AF%E8%A7%86%E5%8C%96%E5%AE%89%E8%A3%85%EF%BC%89&amp;url=/archives/vue-install" width="1" height="1" alt="" style="opacity:0;">
<h2 id="什么是vue">什么是Vue？</h2>
<p>首先了解一下Vue，这里引用官方的介绍：</p>
<blockquote>
 <p>Vue (读音 /vjuː/，类似于 view) 是一套用于构建用户界面的<strong>渐进式框架</strong>。与其它大型框架不同的是，Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层，不仅易于上手，还便于与第三方库或既有项目整合。另一方面，当与<a href="https://cn.vuejs.org/v2/guide/single-file-components.html">现代化的工具链</a>以及各种<a href="https://github.com/vuejs/awesome-vue#libraries--plugins">支持类库</a>结合使用时，Vue 也完全能够为复杂的单页应用提供驱动。</p>
</blockquote>
<p>这段话专业水平有点略高，总之我前端小白是不能太理解的。我基本上把她理解为一个封装了底层JS实现，提供傻瓜式操作的前端框架。也确实如此，使用Vue，我能感觉得到她的方便之处。她可以让一个后台开发人员独立开发一套界面出来（当然，没有前端基础，开发出来的界面肯定没有前端工程师的精彩，也仅仅能用于日常，比如我所要开发的个人博客)，大家可以自行体会。但实际上<strong>Vue并不建议没有前端基础的人使用</strong>，虽然我也想使用HTML+JS+CSS开发一套前端。但学习成本实在太高，目前有心而无力，只能采用这种框架来实现。但在使用Vue的过程中，我会尽力学习学习前端的知识，也当作一次提升的过程。</p>
<blockquote>
 <p><a href="https://cn.vuejs.org/">Vue官网</a>
  <br>
  <a href="https://cn.vuejs.org/v2/guide/">Vue2.x中文文档</a>
  <br>
  <a href="https://github.com/vuejs/vue">VueGitHub</a></p>
</blockquote>
<h2 id="安装前准备">安装前准备</h2>
<p>Vue官方提供有多种安装方式，可以用于不同的场景，可以参考下列文档。</p>
<blockquote>
 <p><a href="https://cn.vuejs.org/v2/guide/installation.html">Vue安装官方文档</a></p>
</blockquote>
<p>可以根据自己的需求选择不同的方式。我推荐使用<a href="https://cn.vuejs.org/v2/guide/installation.html#NPM">NPM安装</a>。本项目也将采用此种方式进行安装。
 <br>
 使用NPM安装需要做以下准备：</p>
<ul>
 <li>Node.Js环境（主要使用NPM包管理器，盖房子需要的各种材料搬运工）</li>
 <li>Vue-cli 脚手架构建工具（就是一个vue项目的构建工具，盖房子需要的地基）</li>
</ul>
<h3 id="一安装nodejs">一、安装NodeJS</h3>
<hr>
<p>想要使用NPM，就需要安装NodeJS。下载链接：<a href="http://nodejs.cn/download/">NodeJS官网</a>。 按照自己的电脑配置进行下载。由于我这里之前有过安装，因此便跳过这个步骤。还未安装的用户可以参考这篇文章。<a href="https://www.runoob.com/nodejs/nodejs-install-setup.html">Node.js 安装配置</a></p>
<h3 id="二设置npm源为国内镜像非必须">二、设置NPM源为国内镜像（非必须）</h3>
<hr>
<p>在国内使用NPM源速度实在感人，如果下载速度太慢，可以考虑将NPM源更换为<a href="https://npm.taobao.org/">淘宝NPM镜像</a>（注：也可以将NPM更换为CNPM，想要更换的用户可以查看<a href="https://npm.taobao.org/">淘宝NPM镜像</a>的使用说明进行更换）</p>
<p>将NPM源更换为淘宝镜像的命令</p>
<blockquote>
 <p>npm config set registry <a href="https://registry.npm.taobao.org">https://registry.npm.taobao.org</a></p>
</blockquote>
<p>修改完成之后，使用下列命令测试</p>
<blockquote>
 <p>npm config get registry</p>
</blockquote>
<p>更改完成图示：
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730094042626.png&amp;size=m" alt="npm源更换"></p>
<h3 id="三安装vue-cli脚手架npm全局安装">三、安装Vue-cli脚手架（npm全局安装）</h3>
<hr>
<p>Vue-cli是一个Vue官方快速构建项目的脚手架，截止目前已经是3.x版本。官网地址<a href="https://cli.vuejs.org/">Vue-CLI脚手架</a></p>
<ol>
 <li>在命令行运行安装命令（-g代表全局安装），等待安装完成。</li>
</ol>
<blockquote>
 <p>3.x安装命令
  <br>
  npm install -g @vue/cli
  <br>
  2.x安装命令，按照个人需求来选择
  <br>
  npm install -g vue/cli</p>
</blockquote>
<ol start="2">
 <li>查看是否安装成功（<strong>V一定要大写</strong>）</li>
</ol>
<blockquote>
 <p>vue -V</p>
</blockquote>
<p>如图所示，则代表Vue安装完成
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730094652201.png&amp;size=m" alt="Vue 安装图示"></p>
<h2 id="自动创建vue项目使用3x的可视化创建">自动创建Vue项目（使用3.x的可视化创建）</h2>
<p>本帖采用Vue-cli 3.x版本的可视化进行创建，如果是2.x版本，可以参考<a href="https://blog.csdn.net/muzidigbig/article/details/80490884">Vue的三种方式安装</a>。这篇文章是以2.x版本为基础进行安装的。</p>
<p>使用可视化创建Vue项目步骤：</p>
<ol>
 <li>使用命令行启动可视化程序</li>
</ol>
<blockquote>
 <p>vue ui</p>
</blockquote>
<p>启动之后会在端口8000上生成一个配置界面（如端口被占用，请先关闭占用端口的程序，具体关闭教程可以百度查找）。启动后的界面如下图所示：
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F2019073009480439.png&amp;size=m" alt="启动界面">
 <br>
 2. 选择“创建”，在这里进行Vue项目的创建。当前是在 E:\Project\vue 目录下进行创建，可以自行选择创建目录。
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730094858339.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIyMjQxOTIz%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;size=m" alt="qwe">
 <br>
 3. 确定好项目目录后，点击“在此创建新项目“，之后按照提示填写项目信息即可。<img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730094949270.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIyMjQxOTIz%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;size=m" alt="qwe">
 <br>
 项目文件夹可以起自己的项目名称
 <br>
 包管理器选择自己想要的包管理。我这里使用NPM进行三方包的管理
 <br>
 其他选项默认即可
 <br>
 4. 点击“下一步”后，需要配置插件和配置，这里根据个人需要进行配置即可。【注：项目创建完成之后也可以添加配置】
 <br>
 <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730095027301.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIyMjQxOTIz%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;size=m" alt="在这里插入图片描述"></p>
<p>下面是我的选择，可以参考一下。</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730095047474.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIyMjQxOTIz%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;size=m" alt="在这里插入图片描述"></p>
<ol start="5">
 <li>
  <p>插件配置，配置完成之后点击“创建项目”即可
   <br>
   <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730095101454.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIyMjQxOTIz%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;size=m" alt="在这里插入图片描述"></p>
 </li>
 <li>
  <p>安装好的项目如图所示
   <br>
   <img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730095125554.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIyMjQxOTIz%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;size=m" alt="在这里插入图片描述"></p>
 </li>
 <li>
  <p>使用开发工具打开安装好的项目，即可开始进行愉快的敲代码了！
   <br>
   输入以下命令启动热编译开发环境</p>
 </li>
</ol>
<blockquote>
 <p>npm run serve</p>
</blockquote>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730095144817.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIyMjQxOTIz%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;size=m" alt="在这里插入图片描述"></p>
<p>如图所示，项目发布在端口8080下，现在我们就去看看吧！</p>
<p><img src="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fimg-blog.csdnimg.cn%2F20190730095210713.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIyMjQxOTIz%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;size=m" alt="在这里插入图片描述">
 <br>
 至此，使用vue-cli 3.x 构建vue项目已经结束。</p>]]></description><guid isPermaLink="false">/archives/vue-install</guid><dc:creator>Takagi</dc:creator><category>文章</category><pubDate>Mon, 8 Jun 2020 11:33:06 GMT</pubDate></item><item><title><![CDATA[Hello,World]]></title><link>https://lixingyong.com/archives/helloworld</link><description><![CDATA[<img src="https://lixingyong.com/plugins/feed/assets/telemetry.gif?title=Hello%2CWorld&amp;url=/archives/helloworld" width="1" height="1" alt="" style="opacity:0;">
<p>据说，第一篇文章是helloworld会带来好运哦！</p>]]></description><guid isPermaLink="false">/archives/helloworld</guid><dc:creator>Takagi</dc:creator><enclosure url="https://lixingyong.com/apis/api.storage.halo.run/v1alpha1/thumbnails/-/via-uri?uri=https%3A%2F%2Fcdn.lixingyong.com%2Fhalo-sakura%2Fimage%2F4afbfbedab64034fa5c6fe07a0c379310a551da3_1591686002904.jpg%3Fx-oss-process%3Dstyle%2Fblog_seal&amp;size=m" type="image/jpeg" length="81461"/><pubDate>Mon, 8 Jun 2020 01:53:58 GMT</pubDate></item></channel></rss>