<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.3">Jekyll</generator><link href="https://yangjava.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://yangjava.github.io/" rel="alternate" type="text/html" /><updated>2023-04-28T09:31:19+00:00</updated><id>https://yangjava.github.io/feed.xml</id><title type="html">yangjava</title><subtitle>yangjava's personal page</subtitle><author><name>杨京京</name></author><entry><title type="html">Torrent文件实现</title><link href="https://yangjava.github.io/2022/11/13/Torrent%E6%96%87%E4%BB%B6%E5%AE%9E%E7%8E%B0/" rel="alternate" type="text/html" title="Torrent文件实现" /><published>2022-11-13T00:00:00+00:00</published><updated>2022-11-13T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/13/Torrent%E6%96%87%E4%BB%B6%E5%AE%9E%E7%8E%B0</id><content type="html" xml:base="https://yangjava.github.io/2022/11/13/Torrent%E6%96%87%E4%BB%B6%E5%AE%9E%E7%8E%B0/">&lt;h1 id=&quot;torrent文件实现&quot;&gt;Torrent文件实现&lt;/h1&gt;
&lt;p&gt;种子文件本质上是文本文件，包含Tracker信息和文件信息两部分。&lt;/p&gt;

&lt;h2 id=&quot;种子定义&quot;&gt;种子定义&lt;/h2&gt;
&lt;p&gt;BitTorrent 协议的种子文件可以保存一组文件的元数据。这种格式的文件被 BitTorrent 协议所定义。扩展名一般为“.torrent”。&lt;/p&gt;

&lt;h2 id=&quot;种子结构&quot;&gt;种子结构&lt;/h2&gt;
&lt;p&gt;.torrent 种子文件本质上是文本文件，包含 Tracker 信息和文件信息两部分。Tracker 信息主要是 BT 下载中需要用到的 Tracker 服务器的地址和针对 Tracker 服务器的设置，文件信息是根据对目标文件的计算生成的，计算结果根据 BitTorrent 协议内的 Bencode 规则进行编码。它的主要原理是需要把提供下载的文件虚拟分成大小相等的块，块大小必须为2k的整数次方（由于是虚拟分块，硬盘上并不产生各个块文件），并把每个块的索引信息和 Hash 验证码写入种子文件中；所以，种子文件就是被下载文件的“索引”。&lt;/p&gt;

&lt;p&gt;Tracker信息主要是BT下载中需要用到的Tracker服务器的地址和针对Tracker服务器的设置；&lt;/p&gt;

&lt;p&gt;文件信息是根据对目标文件的计算生成的，包括以下字段：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;announce - tracker的URL&lt;/li&gt;
  &lt;li&gt;info - 该条映射到一个字典，该字典的键将取决于共享的一个或多个文件：&lt;/li&gt;
  &lt;li&gt;name - 建议保存到的文件和目录名称&lt;/li&gt;
  &lt;li&gt;piece length - 每个文件块的字节数。通常为28 = 256KB = 262144B&lt;/li&gt;
  &lt;li&gt;pieces - 每个文件块的SHA-1的整合Hash。因为SHA-1会返回160-bit的Hash，所以pieces将会得到1个160-bit的整数倍的字符串。和一个length（相当于只有一个文件正在共享）或files（相当于当多个文件被共享）：&lt;/li&gt;
  &lt;li&gt;length - 文件的大小（以字节为单位）&lt;/li&gt;
  &lt;li&gt;files - 一个字典的列表（每个字典对应一个文件）与以下的键：&lt;/li&gt;
  &lt;li&gt;path - 一个对应子目录名的字符串行表，最后一项是实际的文件名称&lt;/li&gt;
  &lt;li&gt;length - 文件的大小（以字节为单位）&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;它的主要原理是需要把提供下载的文件虚拟分成大小相等的块，块大小必须为2k的整数次方（由于是虚拟分块，硬盘上并不产生各个块文件），并把每个块(是块，不是整个文件)的索引信息和Hash验证码写入种子文件中；所以，种子文件就是被下载文件的“索引”。&lt;/p&gt;

&lt;h3 id=&quot;下载启动&quot;&gt;下载启动&lt;/h3&gt;
&lt;p&gt;BT客户端首先解析种子文件得到Tracker地址，然后连接Tracker服务器。
Tracker服务器回应下载者的请求，提供下载者其他下载者（包括发布者）的IP。下载者再连接其他下载者，根据种子文件，两者分别告知对方自己已经有的块，然后交换对方所没有的数据。
此时不需要其他服务器参与，分散了单个线路上的数据流量，因此减轻了服务器负担。&lt;/p&gt;

&lt;h3 id=&quot;防止重复下载&quot;&gt;防止重复下载&lt;/h3&gt;
&lt;p&gt;下载者每得到一个块，需要算出下载块的Hash验证码与种子文件中的对比，如果一样则说明块正确，不一样则需要重新下载这个块。这种规定是为了解决下载内容准确性的问题。&lt;/p&gt;

&lt;h3 id=&quot;下载过程中的变化&quot;&gt;下载过程中的变化&lt;/h3&gt;
&lt;p&gt;用户下载的文件内容越来越完整，对应的，拥有完整种子文件的用户也会越来越多，使文件的“寿命”不断延长。&lt;/p&gt;

&lt;h3 id=&quot;算法扩展&quot;&gt;算法扩展&lt;/h3&gt;
&lt;p&gt;为了解决某些用户“下完就跑”的现象，在非官方BitTorrent协议中还存在一种慢慢开放下载内容的超级种子的算法。&lt;/p&gt;

&lt;h3 id=&quot;网络技术扩展&quot;&gt;网络技术扩展&lt;/h3&gt;
&lt;p&gt;DHT技术可以在无Tracker的情况下下载。
DHT全称为分布式哈希表（Distributed Hash Table），是一种分布式存储方法。在不需要服务器的情况下，每个客户端负责一个小范围的路由，并负责存储一小部分数据，从而实现整个DHT网络的寻址和存储。使用支持该技术的BT下载软件，用户无需连上Tracker就可以下载，因为软件会在DHT网络中寻找下载同一文件的其他用户并与之通讯，开始下载任务。
有些软件（如比特精灵）还会自动通过DHT搜索种子资源，构成种子市场。&lt;/p&gt;

&lt;h2 id=&quot;磁力链接&quot;&gt;磁力链接&lt;/h2&gt;
&lt;p&gt;现在我们使用迅雷等工具下载资源的时候，基本上都只需要一个叫做磁力链接的东西就可以了，非常方便。&lt;/p&gt;

&lt;p&gt;磁力链接格式类似于 magnet:?xt=urn:btih:E7FC73D9E20697C6C440203F5884EF52F9E4BD28&lt;/p&gt;

&lt;p&gt;分解一下这个链接&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;magnet：协议名。&lt;/li&gt;
  &lt;li&gt;xt：exact topic 的缩写，表示资源定位点。BTIH（BitTorrent Info Hash）表示哈希方法名，这里还可以使用 SHA1 和 MD5。这个值是文件的标识符，是不可缺少的。
一般来讲，一个磁力链接只需要上面两个参数即可找到唯一对应的资源。也有其他的可选参数提供更加详细的信息。&lt;/li&gt;
  &lt;li&gt;dn：display name 的缩写，表示向用户显示的文件名。&lt;/li&gt;
  &lt;li&gt;tr：tracker 的缩写，表示 tracker 服务器的地址。&lt;/li&gt;
  &lt;li&gt;kt: 关键字，更笼统的搜索，指定搜索关键字而不是特定文件。&lt;/li&gt;
  &lt;li&gt;mt：文件列表，链接到一个包含磁力链接的元文件 (MAGMA - MAGnet MAnifest）。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;种子-磁力联系&quot;&gt;种子-磁力联系&lt;/h2&gt;
&lt;p&gt;磁力链接的唯一标识符就是 40 个 16 进制字符码，也就是 magnet:?xt=urn:btih:E7FC73D9E20697C6C440203F5884EF52F9E4BD28中的 E7FC73D9E20697C6C440203F5884EF52F9E4BD28。这个同时也是种子文件的 info_hash，是每个种子的唯一标识码。根据它就能将磁力链接于种子联系起来，得到资源的详细信息，进而下载资源。&lt;/p&gt;

&lt;h2 id=&quot;tracker简介&quot;&gt;Tracker简介&lt;/h2&gt;

&lt;p&gt;在BT下载中，有一个非常重要的角色，那就是Tracker服务器。Tracker会追踪有多少人在下载同一文件，并把这些名单发送到BT软件上。BT软件再尝试连接这些用户，以此来给你提供下载速度，同时你也会给他们贡献速度。&lt;/p&gt;

&lt;p&gt;简单来说，Tracker服务器起到的，就是牵线搭桥的作用，而这正是BT下载的核心。越热门、越优质的Tracker，资源解析速度及下载速度就越快。普通BT软件速度不稳定，就是因为内置的Tracker太少。&lt;/p&gt;

&lt;p&gt;opentracker是一个linux中开源和免费的BitTorrent Tracker ，旨在实现一个最小化资源使用，并且可以在无线路由器中使用的轻量级tracker服务器。&lt;/p&gt;

&lt;p&gt;opentracker官网地址：https://erdgeist.org/arts/software/opentracker/&lt;/p&gt;

&lt;h2 id=&quot;dht&quot;&gt;DHT&lt;/h2&gt;
&lt;p&gt;BitTorrent 使用”分布式哈希表”(DHT)来为无 tracker 的种子(torrents)存储 peer 之间的联系信息。这样每个 peer 都成了 tracker。这个协议基于 Kademila 网络并且在 UDP 上实现。DHT 由节点组成，它存储了 peer 的位置。BitTorrent 客户端包含一个 DHT 节点，这个节点用来联系 DHT 中其他节点，从而得到 peer 的位置，进而通过 BitTorrent 协议下载。
peer: 一个 TCP 端口上监听的客户端/服务器，它实现了 BitTorrent 协议。
节点: 一个 UDP 端口上监听的客户端/服务器，它实现了 DHT(分布式哈希表) 协议。&lt;/p&gt;

&lt;h2 id=&quot;python实现下载&quot;&gt;Python实现下载&lt;/h2&gt;
&lt;p&gt;libtorrent是功能齐全的p2p协议开源C ++ bittorrent源码实现，专注于效率和可伸缩性。它可以在嵌入式设备和台式机上运行。它拥有完善的文档库，易于使用。 它提供了client_test可以用于解析torrent种子和磁力链接，可根据磁力链接直接下载文件，对于正在下载的视频文件，用其他播放器可边播放边下载。常见使用libtorrent库的项目有qBittorrent，deluge，Free download manager等。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import libtorrent as lt

# 创建 session 对象
ses = lt.session()
ses.listen_on(6881, 6891)

# 添加磁力链接到下载队列
params = {'save_path': 'D:/demo'}
link = 'magnet:?xt=urn:btih:...'
handle = lt.add_magnet_uri(ses, link, params)

# 等待下载完成
print('downloading metadata...')
while not handle.has_metadata():
    s = handle.status()
    progress = s.progress * 100
    print('%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d)' %
          (progress, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers))


# 开始下载
print('starting', handle.name())
while not handle.is_seed():
    s = handle.status()
    progress = s.progress * 100
    print('%.2f%% complete (down: %.1f kb/s up: %.1f kB/s peers: %d)' %
          (progress, s.download_rate / 1000, s.upload_rate / 1000, s.num_peers))
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;libtorrent源码&quot;&gt;libtorrent源码&lt;/h2&gt;
&lt;p&gt;bt协议有早起的tracker版本（俗称bt1.0）和现在常用的基于DHT的版本（俗称bt2.0），下文为整理的协议相关资料。&lt;/p&gt;</content><author><name>杨京京</name></author><category term="Python" /><summary type="html">Torrent文件实现 种子文件本质上是文本文件，包含Tracker信息和文件信息两部分。</summary></entry><entry><title type="html">Janusgraph图数据库</title><link href="https://yangjava.github.io/2022/11/12/JanusGraph%E5%9B%BE%E6%95%B0%E6%8D%AE%E5%BA%93/" rel="alternate" type="text/html" title="Janusgraph图数据库" /><published>2022-11-12T00:00:00+00:00</published><updated>2022-11-12T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/12/JanusGraph%E5%9B%BE%E6%95%B0%E6%8D%AE%E5%BA%93</id><content type="html" xml:base="https://yangjava.github.io/2022/11/12/JanusGraph%E5%9B%BE%E6%95%B0%E6%8D%AE%E5%BA%93/">&lt;h1 id=&quot;janusgraph&quot;&gt;JanusGraph&lt;/h1&gt;
&lt;p&gt;JanusGraph是一个可扩展的图形数据库，用于存储和查询分布在多机集群中的包含数千亿顶点和边的图形。该项目由Titan出资，并于2017年由Linux基金会(Linux Foundation)开放管理。&lt;/p&gt;

&lt;h2 id=&quot;常见图库对比&quot;&gt;常见图库对比&lt;/h2&gt;
&lt;p&gt;目前主流数据库分为两个派系：Neo4j派 和 Tinkerpop派&lt;/p&gt;

&lt;h2 id=&quot;janusgraph-与-tinkerpop-与-gremlin&quot;&gt;JanusGraph 与 Tinkerpop 与 Gremlin&lt;/h2&gt;
&lt;p&gt;Tinkerpop 是Apache基金会下的一个开源的图数据库与图计算框架（OLTP与OLAP）。&lt;/p&gt;

&lt;p&gt;Gremlin 是Tinkerpop的一个组件，它是一门路径导向语言，用于图操作和图遍历（也称查询语言）。Gremlin Console 和 Gremlin Server 分别提供了控制台和远程执行Gremlin查询语言的方式。Gremlin Server 在 JanusGraph 中被成为 JanusGraph Server。&lt;/p&gt;

&lt;p&gt;JanusGraph是基于Tinkerpop这个框架来开发的，使用的查询语言也是Gremlin。&lt;/p&gt;

&lt;h2 id=&quot;janusgraph概述&quot;&gt;JanusGraph概述&lt;/h2&gt;
&lt;p&gt;JanusGraph是一个图形数据库引擎。其本身专注于紧凑图序列化、丰富图数据建模、高效的查询执行。另外，JanusGraph利用Hadoop进行图分析和批处理图处理。JanusGraph为数据持久性、数据索引、客户端访问实现了强大的模块化接口。JanusGraph的模块化体系结构使其可以与多种存储、索引、客户端技术进行互操作。它还简化了扩展JanusGraph以支持新的过程。&lt;/p&gt;

&lt;h2 id=&quot;交互&quot;&gt;交互&lt;/h2&gt;
&lt;p&gt;应用程序可以通过两种方式与JanusGraph交互：&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;嵌入式： 将JanusGraph嵌入到自己的图Gremlin查询应用中，与自己的应用公用同一JVM。
查询执行时，JanusGraph的缓存和事务处理都在与应用程序相同的JVM中进行，当数据模型大时，很容易OOM，并且耦合性太高，生产上一般不这么搞。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;服务式： JanusGraph单独运行在一个或一组服务器上，对外提供服务。（推荐的模式）
客户端通过向服务器提交Gremlin查询，与远程JanusGraph实例进行交互。&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;docker安装janusgraph&quot;&gt;Docker安装JanusGraph&lt;/h2&gt;
&lt;p&gt;JanusGraph提供Docker image。 Docker使得在单台机器上安装和运行Janusgraph服务和客户端变得简单容易。有关Janusgraph的安装和使用说明请参照 docker guide。
下面就举例如何使用Docker技术来安装和运行JanusGraph:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ docker run -it -p 8182:8182 janusgraph/janusgraph
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;运行docker命令，获取janusgraph的Dockerimage并运行于Docker容器，8182端口作为服务端口暴露对外。启动日志如下:&lt;/p&gt;

&lt;p&gt;等待服务启动完成后，就可以启动Gremlin Console来连接新安装的janusgraph server:
Gremlin Console是一个交互式shell，允许您访问JanusGraph图数据。你可以通过运行位于项目的bin目录中的gremlin.sh脚本来运行。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ bin/gremlin.sh

         \,,,/
         (o o)
-----oOOo-(3)-oOOo-----
gremlin&amp;gt; :remote connect tinkerpop.server conf/remote.yaml
==&amp;gt;Configured localhost/127.0.0.1:8182
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Gremlin Console命令采用的是Apache Groovy,。Gremlin-Groovy集成自Groovy提供了许多基本或高级的图遍历方法。&lt;/p&gt;

&lt;p&gt;为了方便起见，这里在同一台机器同时安装JanusGraph Server和Gremlin Console Client，首先在机器上创建Docker容器来运行JanusGraph Server:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ docker run --name janusgraph-default janusgraph/janusgraph:latest
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;然后在这台机器上再另启一个容器来运行Gremlin Console Client并连接运行中的Janusgraph Server。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ docker run --rm --link janusgraph-default:janusgraph -e GREMLIN_REMOTE_HOSTS=janusgraph \
    -it janusgraph/janusgraph:latest ./bin/gremlin.sh

         \,,,/
         (o o)
-----oOOo-(3)-oOOo-----
gremlin&amp;gt; :remote connect tinkerpop.server conf/remote.yaml
==&amp;gt;Configured janusgraph/172.17.0.2:8182
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Gremlin server启动完成后，默认端口是8182。下面我们启动Gremlin Console使用如下:remote的远程连接命令，将Gremlin Console连接到Server上。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;gremlin&amp;gt; :remote connect tinkerpop.server conf/remote.yaml
==&amp;gt;Configured localhost/127.0.0.1:8182
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;从日志中可以看出，在本例中，客户机和服务器运行在同一台机器上。当使用不同的设置时，您所要做的就是修改conf/remote.yaml文件。&lt;/p&gt;

&lt;h2 id=&quot;将图加载到janusgraph&quot;&gt;将图加载到JanusGraph&lt;/h2&gt;
&lt;p&gt;将一个图数据加载到Janusgraph主要通过JanusGraphFactory和JanusGraphFactory两个类。首先利用JanusGraphFactory提供的静态open方法，以配置文件路径作为输入参数，运行并返回graph实例(示例中的配置参考配置参考章节中介绍)。然后利用GraphOfTheGodsFactory的load方法并将返回的graph实例作为参数运行，从而完成图加载到JanusGraph中。&lt;/p&gt;

&lt;p&gt;将图加载到带索引后端的Janusgraph
下面的conf/janusgraph-berkeleyje-es.properties配置文件配置的是以BerkeleyDB作为存储后端，Elasticsearch作为索引后端的Janusgraph。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;gremlin&amp;gt; graph = JanusGraphFactory.open('conf/janusgraph-berkeleyje-es.properties')
==&amp;gt;standardjanusgraph[berkeleyje:../db/berkeley]
gremlin&amp;gt; GraphOfTheGodsFactory.load(graph)
==&amp;gt;null
gremlin&amp;gt; g = graph.traversal()
==&amp;gt;graphtraversalsource[standardjanusgraph[berkeleyje:../db/berkeley], standard]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;JanusGraphFactory.open()和GraphOfTheGodsFactory.load()完成以下操作&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;为图创建全局和vertex-centric的索引集合。&lt;/li&gt;
  &lt;li&gt;加载所有的顶点及其属性。&lt;/li&gt;
  &lt;li&gt;加载所有的边及其属性。&lt;/li&gt;
&lt;/ul&gt;</content><author><name>杨京京</name></author><category term="JanusGraph" /><summary type="html">JanusGraph JanusGraph是一个可扩展的图形数据库，用于存储和查询分布在多机集群中的包含数千亿顶点和边的图形。该项目由Titan出资，并于2017年由Linux基金会(Linux Foundation)开放管理。</summary></entry><entry><title type="html">Windwo子系统实战</title><link href="https://yangjava.github.io/2022/11/11/Windwo%E5%AD%90%E7%B3%BB%E7%BB%9F%E5%AE%9E%E6%88%98/" rel="alternate" type="text/html" title="Windwo子系统实战" /><published>2022-11-11T00:00:00+00:00</published><updated>2022-11-11T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/11/Windwo%E5%AD%90%E7%B3%BB%E7%BB%9F%E5%AE%9E%E6%88%98</id><content type="html" xml:base="https://yangjava.github.io/2022/11/11/Windwo%E5%AD%90%E7%B3%BB%E7%BB%9F%E5%AE%9E%E6%88%98/">&lt;h1 id=&quot;window子系统实战&quot;&gt;Window子系统实战&lt;/h1&gt;
&lt;p&gt;Windows Subsystem for Linux（WSL）是一个用于在本地运行linux二进制可执行文件（ELF格式）的兼容层。&lt;/p&gt;

&lt;h2 id=&quot;wsl简介&quot;&gt;WSL简介&lt;/h2&gt;
&lt;p&gt;Windows Subsystem for Linux（WSL）是一个用于在本地运行linux二进制可执行文件（ELF格式）的兼容层。与虚拟机相比，wsl没有虚拟硬件的过程，而是直接在windows上虚拟一个linux内核，模拟linux系统调用，以运行linux执行文件。
因此效率要比虚拟机高，但是它使用的是自己实现的init进程而不是发行版的init进程，并且几乎没有实现任何系统服务，因此只适用于软件的开发，而不是作为桌面环境或生产性的服务器。&lt;/p&gt;

&lt;p&gt;并且wsl的目的也是如此，可以简单的将它理解为可以运行linux可执行文件的、类似于powershell的shell，具有互操作性（在linux中执行windows命令，在windows中执行linux命令）。&lt;/p&gt;

&lt;h2 id=&quot;wsl组件&quot;&gt;WSL组件&lt;/h2&gt;
&lt;p&gt;wsl实现的组件涉及到了用户和内核模式。在Windows NT内核模式中，LXCore，LXSS这两个驱动提供了linux内核调用的实现，即将linux调用转化为对应的windows NT内核调用；还提供了两种文件系统：VolFs（挂载在/目录上，支持linux文件系统所有特性）和DriverFs（挂载在/mnt/c，/mnt/d等等windows分区，主要为了支持系统间的互操作性）；驱动还会模拟内核的行为，对linux进程进行调度。&lt;/p&gt;

&lt;p&gt;在用户模式下，windows提供了一种特殊的进程类型：Pico进程，来支持linux进程的运行。windows会 “放松” 对该类型进程的控制，主要交由linux虚拟内核调用和管理，即隔离性（因此需要系统的支持，低版本的系统不能使用wls的功能）。pico会将ELF二进制可执行文件装入到自己的地址空间，然后执行在linux虚拟内核提供的兼容层上。一个pico对应一个linux进程，并且pico进程也是windows的一种特殊进程，因此你可以在任务管理器上看到linux进程。&lt;/p&gt;

&lt;p&gt;无论exe还是elf格式的二进制文件，原理上都可以在同架构的cpu上执行，只是结构不同操作系统不能解析罢了。而Pico能够解析ELF格式的二进制文件，只需要linux虚拟内核能够提供正确的系统调用，就能够运行大部分linux命令。&lt;/p&gt;

&lt;p&gt;LXSS管理服务主要用于协调windows和linux进程之间的关系，和给于Bash.exe（并不是shell，只是我们访问wsl的入口）调用linux命令的接口。所有的运行的linux进程都会被加入到叫Linux实例（应该有LXSS记录的）中，只有第一次请求访问linux进程时才会创建Linux实例，才会创建init进程；当window关机时，会自动关闭linux实例，即关闭linux所有进程。&lt;/p&gt;

&lt;p&gt;也就是wsl不会随windows系统自启而自启，同时没有使用发行版的init进程，导致wsl中没有服务的存在。&lt;/p&gt;

&lt;h2 id=&quot;wsl运行过程&quot;&gt;WSL运行过程&lt;/h2&gt;
&lt;p&gt;linux中正常的启动过程是引导程序载入内核，内核初始化后载入init进程，init进程开启各项服务，将系统配置到用户可用的状态，如多用户登录、图形界面登录等。此时linux自启完成，接着等待用户的登录，并且登录方式多种，如控制台登录、ssh登录、虚拟终端登录等等。&lt;/p&gt;

&lt;p&gt;而wsl并不是一个真正的系统，而只是windows的一部分，可以执行linux二进制可执行文件。内核也是虚拟出来的，但是具有一定隔离性，如linux进程由虚拟内核调度，也具有互操作性。&lt;/p&gt;

&lt;p&gt;因此当windows自启结束并加载了上述LxCore、LXSS两个驱动后，已经能够提供linux进程系统调用了。此时wsl的init进程（windows自己实现的）并不会立刻运行，即暂时没有一个linux实例。只有当第一次访问wsl时（执行Bash.exe），才会创建linux实例，执行init服务进程。这个init进程会伴随linux实例，直到实例结束。然后再创建bash shell 和 另一个init 进程，在本次会话结束时（关闭Bash.exe窗口）这两个进程结束。之后再通过Bash.exe连接wsl，都只会创建bash和右边的init进程。&lt;/p&gt;

&lt;h2 id=&quot;文件系统&quot;&gt;文件系统&lt;/h2&gt;
&lt;p&gt;wsl只有两种windows设计的文件系统：VolFs和DriverFs。其中VolFs文件系统主要是为了支持linux文件系统的全部特性，如linux的文件权限、符号链接、不同于windows的文件名、文件名大小写敏感等等。&lt;/p&gt;

&lt;p&gt;而DriveFs主要是为了挂载windows的分区，并且实现互操作性而存在。实际上就是NTFS文件系统的包装，能够让NTFS在linux中使用，即使也提供了大部分linux文件系统特性，但是限制很多，如：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;文件目录权限全为777，实际上就算是root用户，在windows分区中也只有打开Base.exe命令拥有者的权限。说明普通用户使用root权限也不能修改c盘中大部分文件。&lt;/li&gt;
  &lt;li&gt;最好不要在windows下创建文件名只有大小写不同的文件，尽管NTFS支持了。&lt;/li&gt;
  &lt;li&gt;支持linux符号链接，为windows可执行文件创建符号链接时，注意添加后缀.exe。不要与windows的快捷方式混淆，它们目的一致，但结构不一致，不能在linux中使用。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;禁忌&quot;&gt;禁忌&lt;/h2&gt;
&lt;p&gt;不要在任何情况下，使用windows工具访问、创建、修改linux发行版的文件。再安装了WSL后，可以在C盘中找到它的根目录，含有linux标准目录结构，但千万不要修改它。&lt;/p&gt;

&lt;p&gt;linux和windows文件系统的数据存放形式是不同的，为了支持linux文件系统，wsl实现了VolFs。VolFs本质上还是使用了windows的NTFS的文件格式（因此你能够找到它），只是将Linux文件的元数据放入NTFS文件的扩展属性中。因此linux文件系统可以正常执行，而在windows看来，它的文件不存在或者空；而使用windows修改它的文件时，不会保留它的扩展属性，导致在linux中看起来不正常。&lt;/p&gt;

&lt;p&gt;因此，如果想要实现两个系统的互操作，应该将工作目录置于windows分区内，linux文件夹外，在windows的文件夹中操作。&lt;/p&gt;

&lt;h2 id=&quot;wsl使用&quot;&gt;WSL使用&lt;/h2&gt;
&lt;p&gt;wsl需要系统支持，安装之前最好将系统更新到最新版。&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;开启linux子系统（WSL），使用管理员权限打开PowerShell，运行：
    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;重启&lt;/li&gt;
  &lt;li&gt;安装发行版，这里使用Ubuntu。打开应用商店，然后下载&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;按win键，找到ubuntu，点击运行，它会进行初始化。然后提示输入普通用户名和密码，这是默认登录用户。ubuntu中默认root用户不能登录。&lt;/p&gt;

&lt;h2 id=&quot;用户账户和权限&quot;&gt;用户账户和权限&lt;/h2&gt;
&lt;p&gt;wsl与windows有一定隔离性，wsl的用户对linux文件、进程的权限与linux一致。但对于/mnt/c下windows的最高访问权限取决于运行Base.exe（即使使用Ubuntu.exe，最终一致）拥有者的权限。即普通windows用户以root身份运行wsl也不能随意删除、访问、修改c盘文件。&lt;/p&gt;

&lt;h2 id=&quot;wsl管理&quot;&gt;wsl管理&lt;/h2&gt;
&lt;p&gt;有三种运行wsl的方法：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;发行版提供的app，如ubuntu：进入到linux家目录&lt;/li&gt;
  &lt;li&gt;wsl.exe或bash.exe：linux置当前目录为工作目录&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;wsl [command]&lt;/code&gt; 或 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bash -c [command]&lt;/code&gt;：运行linux命令，当前目录作为工作目录&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;wsl中可以存在多个发行版，通过wslconfig管理，wslconfig /?可以查看具体功能：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;wslconfig /list [/all]：列出已注册的发行版，/all额外列出正在安装和卸载的发行版。
wslconfig /setdefault：设置运行wsl时的默认发行版
wslconfig /unregister：卸载发行版
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;具体的发行版提供的入口，如ubuntu，可以设置默认用户，详细参考ubuntu /?&lt;/p&gt;

&lt;h2 id=&quot;互操作&quot;&gt;互操作&lt;/h2&gt;
&lt;p&gt;上面多次提到互操作性，也就是可以在windows中运行linux进程，在linux中运行windows进程，并且支持两个不同进程间的输入输出重定向。&lt;/p&gt;

&lt;p&gt;在windows中使用&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;wsl [command]&lt;/code&gt;运行linux命令，需要注意：&lt;/p&gt;

&lt;p&gt;linux命令使用当前目录作为工作目录
对于windows文件，拥有运行WSL的windows用户权限；对于linux文件拥有登录用户权限
文件路径使用linux格式
例子：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;C:\temp&amp;gt; wsl ls -la
&amp;lt;- contents of C:\temp -&amp;gt;

C:\temp&amp;gt; wsl sudo apt-get update
[sudo] password for username:
Hit:1 https://archive.ubuntu.com/ubuntu xenial InRelease
Get:2 https://security.ubuntu.com/ubuntu xenial-security InRelease [94.5 kB]

C:\temp&amp;gt; wsl ls -la | findstr &quot;foo&quot;
-rwxrwxrwx 1 root root     14 Sep 27 14:26 foo.bat

C:\temp&amp;gt; dir | wsl grep foo
09/27/2016  02:26 PM                14 foo.bat

C:\temp&amp;gt; wsl ls -la &amp;gt; out.txt

C:\temp&amp;gt; wsl ls -la /proc/cpuinfo
-r--r--r-- 1 root root 0 Sep 28 11:28 /proc/cpuinfo

C:\temp&amp;gt; wsl ls -la &quot;/mnt/c/Program Files&quot;
&amp;lt;- contents of C:\Program Files -&amp;gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;在linux中运行windows命令，使用[binary name].exe（后缀不要省略），linux可以直接访问windows命令的原因在于linux共享了windows的PATH环境变量（我猜是linux中唯一的守护进程init做的）。需要注意：&lt;/p&gt;

&lt;p&gt;一般windows命令的工作目录为当前linux的工作目录。如果linux工作目录位于linux文件系统内，则windows的工作目录会改为Base.exe的工作目录（原因见2.4小节）。
拥有与运行WSL拥有者一致的权限
需要注意路径，看下面的例子&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ notepad.exe

$ ipconfig.exe | grep IPv4 | cut -d: -f2
172.21.240.1
10.159.21.24

$ ls -la | findstr.exe foo.txt

$ cmd.exe /c dir
&amp;lt;- contents of C:\ -&amp;gt;

$#cmd 原生命名需要通过cmd.exe运行
$ cmd.exe /C dir
&amp;lt;- contents of C:\ -&amp;gt;

$ PING.EXE www.microsoft.com
Pinging e1863.dspb.akamaiedge.net [2600:1409:a:5a2::747] with 32 bytes of data:
Reply from 2600:1409:a:5a2::747: time=2ms

$ notepad.exe &quot;C:\temp\foo.txt&quot;
$ notepad.exe C:\\temp\\foo.txt

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;wsl默认账号&quot;&gt;WSL默认账号&lt;/h2&gt;
&lt;p&gt;wsl创建完成后，是通过自定义的用户和密码进行登录的，而并没有设置root的密码，但很多情况下，都需要切换到root来操作，每次都sudo也不很方便。
那，如果想登录wsl的时候就以root登录该如何设置呢？&lt;/p&gt;

&lt;p&gt;首先，我们找到ubuntu.exe的路径，比如我这里是“C:\Program Files\WindowsApps\CanonicalGroupLimited.Ubuntu20.04onWindows_2004.2021.222.0_x64__79rhkp1fndgsc\ubuntu2004.exe”，切换到该路径后，&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;ubuntu.exe config --default-user root
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;重新打开wsl后发现，登录即为root用户。&lt;/p&gt;</content><author><name>杨京京</name></author><category term="OS" /><summary type="html">Window子系统实战 Windows Subsystem for Linux（WSL）是一个用于在本地运行linux二进制可执行文件（ELF格式）的兼容层。</summary></entry><entry><title type="html">Vscode实战</title><link href="https://yangjava.github.io/2022/11/10/Vscode%E5%AE%9E%E6%88%98/" rel="alternate" type="text/html" title="Vscode实战" /><published>2022-11-10T00:00:00+00:00</published><updated>2022-11-10T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/10/Vscode%E5%AE%9E%E6%88%98</id><content type="html" xml:base="https://yangjava.github.io/2022/11/10/Vscode%E5%AE%9E%E6%88%98/">&lt;h1 id=&quot;vscode实战&quot;&gt;VsCode实战&lt;/h1&gt;

&lt;h2 id=&quot;vscodewsldocker-开发环境构建指南&quot;&gt;VsCode+WSL+Docker 开发环境构建指南&lt;/h2&gt;

&lt;h3 id=&quot;why为什么整这种活&quot;&gt;Why——为什么整这种活&lt;/h3&gt;
&lt;p&gt;在实际开发中，我们遇到了以下类型的问题：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;不同工程对nodejs版本要求不一样
比如我们的工程A是基于angularjs1.5的，它要求nodejs版本为11.0.0， 而工程B是基于vue+vite的，vite要求nodejs版本需要大于12.0.0。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;某些npm包需要linux编译环境
典型地，如node-sass这个包，所以需要本地具有可以编译它的环境，比如python，gyp等等，但是一般来说，我们的Windows上并没有这些环境，所以就会报一堆错，而Windows如果想要安装这种环境，又需要安装一些很冷门还很难装的软件与库，搞得及其烦人。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;需要适应未来DevOps转型
现在很多大厂已经转型DevOps了，云计算和容器化是一种大趋势，随着业务量与项目数量的增长，开发和运维都面临着向DevOps的转型，所以提前进行容器化开发，可以为未来容器化开发——容器化部署模式铺平道路。&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;方案简述&quot;&gt;方案简述&lt;/h2&gt;
&lt;p&gt;我们采用Vscode + Docker + WSL来解决上述问题。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;VsCode :不必多介绍，一款流行的编辑器，在本方案中，它只需要安装两个插件即可：&lt;/li&gt;
  &lt;li&gt;Remote-Containers :用于连接远程容器&lt;/li&gt;
  &lt;li&gt;Remote-WSL :用于连接本地的WSL&lt;/li&gt;
  &lt;li&gt;WSL（windows subsystem linux）:Windows系统下的Linux子系统，它在这里主要起的作用是用来提供一个linux环境，一是提供给docker作为运行环境，二是用来解决上述某些npm包需要linux编译环境的问题。&lt;/li&gt;
  &lt;li&gt;Docker :一款容器应用，它可以提供比虚拟机更加快捷和对硬件资源消耗更少的虚拟化方案，为我们的提供一个虚拟的服务器和开发环境。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;安装配置wsl-20版本&quot;&gt;安装配置WSL 2.0版本&lt;/h2&gt;
&lt;p&gt;最新的Windws10默认都是直接支持WSL2的，我们只需要在windows应用商店搜索linux，就能看到支持的Linux子系统列表，选择其中一个安装就可以了。&lt;/p&gt;

&lt;p&gt;当然，推荐的话，还是ubuntu比较流行，遇到问题也比较容易搜索到相关解决方案。 为了更好地操作，推荐在应用商店中搜索windows terminal安装。&lt;/p&gt;

&lt;p&gt;另外，由于WSL是基于Hype-V技术的，需要Windows开启相关功能，并且保证BIOS中的虚拟化选项开启，由于不同电脑BIOS的设置方式不同，请自行在网络上搜索相关设置方法。&lt;/p&gt;

&lt;p&gt;如何判断电脑是否开启了虚拟化呢？ 打开任务管理器，切换到【性能】一栏，可以看到【CPU】下面的信息中标识了是否开启了虚拟化：&lt;/p&gt;

&lt;p&gt;输入以下命令：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;wsl -l --verbose
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;会列出本机现在安装的所有WSL发行版以及它的版本&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;  NAME      STATE           VERSION
* Ubuntu    Running         2
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;系统默认的那个发行版前会有一个*号，也就是，当你在windows Terminal中直接输入wsl时，打开的那个发行版：&lt;/p&gt;

&lt;h2 id=&quot;安装配置docker&quot;&gt;安装配置Docker&lt;/h2&gt;
&lt;p&gt;Windows需要去官网下载Docker desktop最新版本，下载安装文件后直接安装即可。
https://docs.docker.com/desktop/windows/wsl/
安装好之后，我们要进行以下配置，运行docker-desktop程序&lt;/p&gt;

&lt;p&gt;修改一下docker镜像源和配置：&lt;/p&gt;
&lt;div class=&quot;language-json highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;registry-mirrors&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;http://hub-mirror.c.163.com&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;https://docker.mirrors.ustc.edu.cn&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;insecure-registries&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[],&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;debug&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;experimental&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;false&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;features&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;buildkit&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;builder&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;gc&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;enabled&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;&quot;defaultKeepStorage&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;20GB&quot;&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;安装配置vscode相关插件&quot;&gt;安装配置VsCode相关插件&lt;/h2&gt;

&lt;h2 id=&quot;在wsl容器中开发调试应用&quot;&gt;在WSL容器中开发调试应用&lt;/h2&gt;
&lt;p&gt;自动创建容器
插件安装成功后，在VsCode中打开工程目录，会看到左下角有两个相对的箭头的标识，点击它，就会弹出命令选项，让我们选择在哪里打开：&lt;/p&gt;

&lt;p&gt;在确保docker desktop 正常运行的前提下，我们可以选择在WSL中开发目录，也可以选择在容器内打开当前工程目录，这里我们选择在容器内打开。它会让我们选择要打开的目录，默认为当前目录：&lt;/p&gt;

&lt;p&gt;VsCode在配置好相关环境后，会在当前目录下生成一个一个名为.devcontainer的文件夹，里面存放着容器的环境配置，有了这个配置，下次再在容器中打开工程目录时，就不会再让我们选择工程环境类型了。&lt;/p&gt;

&lt;p&gt;当然，为了不污染项目文件，可以把这个目录加入到.gitignore文件中。&lt;/p&gt;

&lt;p&gt;之后，我们就可以像在本地开发一样，在容器内进行开发了。&lt;/p&gt;

&lt;p&gt;手动创建容器
我们发现，在选择NodeJS版本那一步，只有少数几个版本，比如我们需要10.17.0的话，这里就没有，怎么办呢，我们有另一种方式。&lt;/p&gt;

&lt;p&gt;在工程根目录下新建Dockerfile文件，&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;FROM node:10.17.0 # 这里写上需要的nodejs版本

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 8090 # 这里是应用在开发时默认运行的端口

CMD [ &quot;npm&quot;, &quot;run&quot;, &quot;serve&quot;]  # 拆解的开发命令 npm run serve
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;然后新建docker忽略文件.dockerignore :&lt;/p&gt;

&lt;p&gt;node_modules
npm-debug.log
新建后，点击左下角远程容器按钮，选择【在WSL中打开】：&lt;/p&gt;

&lt;h2 id=&quot;软硬件要求&quot;&gt;软硬件要求&lt;/h2&gt;
&lt;p&gt;官方System requirements文档&lt;/p&gt;

&lt;p&gt;BIOS开启虚拟化
添加Hyper-V（win10家庭版需要安装）
WSL安装（控制台输入WSL -l检查是否安装，下载地址：WSL安装更新）
将默认安装的Linux子系统版本设置为WSL2（控制台输入wsl.exe –set-default-version 2）
4GB系统内存
64位处理器带二级地址翻译（SLAT）&lt;/p&gt;

&lt;h2 id=&quot;下载安装&quot;&gt;下载安装&lt;/h2&gt;
&lt;p&gt;下载Docker Desktop(各版本下载地址：docker desktop release-notes)，按正常的客户端程序安装即可，4.9+版本目前有不少小问题，可到官方的issue页面检索相关问题（https://github.com/docker/for-win/issues）；&lt;/p&gt;

&lt;h1 id=&quot;参考资料&quot;&gt;参考资料&lt;/h1&gt;
&lt;p&gt;https://docs.docker.com/desktop/windows/wsl/&lt;/p&gt;</content><author><name>杨京京</name></author><category term="VsCode" /><summary type="html">VsCode实战</summary></entry><entry><title type="html">Python实战hive</title><link href="https://yangjava.github.io/2022/11/09/Python%E5%AE%9E%E6%88%98Hive/" rel="alternate" type="text/html" title="Python实战hive" /><published>2022-11-09T00:00:00+00:00</published><updated>2022-11-09T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/09/Python%E5%AE%9E%E6%88%98Hive</id><content type="html" xml:base="https://yangjava.github.io/2022/11/09/Python%E5%AE%9E%E6%88%98Hive/">&lt;h1 id=&quot;python实战hive&quot;&gt;Python实战Hive&lt;/h1&gt;
&lt;p&gt;PyHive 是 Python 语言编写的用于操作 Hive 的简便工具库。&lt;/p&gt;

&lt;h2 id=&quot;pyhive安装&quot;&gt;PyHive安装&lt;/h2&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# Liunx系统
pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive

# Windows系统会出现莫名其妙的报错,sasl需要选择对应的版本号
pip install sasl‑0.3.1‑cp310‑cp310‑win_amd64.whl
或者下载到本地手动导入包
pip install D:\sasl-0.3.1-cp310-cp310-win_amd64.whl

优化后导入如下：
pip install sasl-0.2.1-cp36-cp36m-win_amd64.whl
pip install thrift -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install thrift_sasl==0.3.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pyhive -i https://pypi.tuna.tsinghua.edu.cn/simple
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;下载一个对应你所使用的Python版本和Windows版本的sasl文件：https://www.lfd.uci.edu/~gohlke/pythonlibs/#sasl。
例如， sasl‑0.2.1‑cp36‑cp36m‑win_amd64.whl，它对应的Python 版本为3.6，对应的Windows系统为64位。 安装执行pip install sasl-0.2.1-cp37-cp37m-win_amd64.whl&lt;/p&gt;

&lt;h2 id=&quot;简介&quot;&gt;简介&lt;/h2&gt;
&lt;p&gt;pyhive通过与HiveServer2通讯来操作Hive数据。当hiveserver2服务启动后，会开启10000的端口，对外提供服务，此时pyhive客户端通过JDBC连接hiveserver2进行Hive sql操作。&lt;/p&gt;

&lt;p&gt;Pyhive Client通过JDBC与hiveserver2建立通信，hiveserver2服务端发送HQL语句到Driver端，Driver端将HQL发送至Compiler组件进行语法树解析，此时需在metastore获取HQL相关的database和table等信息，在对HQL完成解析后，Compiler组件发送执行计划至Driver端等待处理，Driver端发送执行计划至Executor端，再由Executor端发送MapReduce任务至Hadoop集群执行Job，Job完成后最终将HQL查询数据发送Driver端，再由hive server2返回数据至pyhive Client。&lt;/p&gt;

&lt;h2 id=&quot;访问&quot;&gt;访问&lt;/h2&gt;
&lt;p&gt;PyHive 连接 Hive 一般流程：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;创建连接&lt;/li&gt;
  &lt;li&gt;获取游标&lt;/li&gt;
  &lt;li&gt;执行SQL语句&lt;/li&gt;
  &lt;li&gt;获取结果&lt;/li&gt;
  &lt;li&gt;关闭连接&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 加载包
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pyhive&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hive&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 建立连接
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;connect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;host&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'10.8.1.2'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# 主机
&lt;/span&gt;                    &lt;span class=&quot;n&quot;&gt;port&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;                  &lt;span class=&quot;c1&quot;&gt;# 端口 
&lt;/span&gt;                    &lt;span class=&quot;n&quot;&gt;username&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'hdfs'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;                  &lt;span class=&quot;c1&quot;&gt;# 用户
&lt;/span&gt;                    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                    
&lt;span class=&quot;c1&quot;&gt;# 查询
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;conn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 获取一个游标
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;execute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'show databases'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 执行sql语句
# sql = 'show tables'  # 操作语句
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fetchall&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 输出获取结果的所有行
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
 
&lt;span class=&quot;c1&quot;&gt;# 关闭连接
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;close&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;close&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;其中，cursor.fetchall() 返回的是一个 list 对象，并且每一个元素都是一个 tuple 对象。 需要对其进行一定的处理，才能转换为建模需要的 DataFrame。&lt;/p&gt;

&lt;h2 id=&quot;函数封装&quot;&gt;函数封装&lt;/h2&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 函数封装
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sql_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;is_all_col&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;'''
    is_all_col: 是否选取所有的列 select *
    '''&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# 建立连接
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;con&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;connect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;host&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'ip'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;port&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'port'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;auth&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'auth'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;kerberos_service_name&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'kerberos_service_name'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;database&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'database'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;password&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'password'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;con&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;execute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sql_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# 列名
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;col_tmp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;description&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;is_all_col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'.'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# 数据
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fetchall&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;columns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# 关闭连接 释放资源
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;cursor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;close&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;con&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;close&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__name__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'__main__'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;

    &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pandas&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;
    &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;s&quot;&gt;'ip'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'xxx.xxx.xxx.xxx'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;s&quot;&gt;'port'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'1000'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;s&quot;&gt;'auth'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'hider'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;s&quot;&gt;'kerberos_service_name'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'hive'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;s&quot;&gt;'database'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'hive'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;s&quot;&gt;'password'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'100'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;sql_text1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'select * from table limit 5'&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sql_text2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'select a, b, c from table limit 5'&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# 所有列
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;data1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;get_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sql_text1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;is_all_col&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# 指定列
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;data2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;get_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sql_text2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;is_all_col&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;hive配置&quot;&gt;Hive配置&lt;/h2&gt;
&lt;p&gt;Hive 有许多必要的参数设置，通过 Connection 类的 configuration 参数可进行配置。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;hive_config = {
    'mapreduce.job.queuename': 'my_hive',
    'hive.exec.compress.output': 'false',
    'hive.exec.compress.intermediate': 'true',
    'mapred.min.split.size.per.node': '1',
    'mapred.min.split.size.per.rack': '1',
    'hive.map.aggr': 'true',
    'hive.groupby.skewindata': 'true',
    'hive.exec.dynamic.partition.mode': 'nonstrict'
}

conn = hive.connect(host = '',
                    port = '',
                    ...
                    configuration = hive_config)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;列名&quot;&gt;列名&lt;/h2&gt;
&lt;p&gt;Cursor 类中有一个 description 方法，可以获取数据表中的列名、数据类型等信息。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;col = cursor.description
col_names = list()
for column in col:
	col_names.append(column[0]) # 提取第一个元素：列名
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;执行脚本带参数&quot;&gt;执行脚本带参数&lt;/h2&gt;
&lt;p&gt;游标所执行的脚本可以不写死，通过参数的方式进行配置。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;month = 202205

# %占位符
sql_text = 'select * from table where month = %d limit 5' % month
print(sql_text)

# format
sql_text = 'select * from table where month = {} limit 5'.format(month)

# f-string
sql_text = f'select * from table where month = {month} limit 5'
print(sql_text)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;</content><author><name>杨京京</name></author><category term="Python" /><category term="Hive" /><summary type="html">Python实战Hive PyHive 是 Python 语言编写的用于操作 Hive 的简便工具库。</summary></entry><entry><title type="html">Pyspark实战</title><link href="https://yangjava.github.io/2022/11/08/Pyspark%E5%AE%9E%E6%88%98/" rel="alternate" type="text/html" title="Pyspark实战" /><published>2022-11-08T00:00:00+00:00</published><updated>2022-11-08T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/08/Pyspark%E5%AE%9E%E6%88%98</id><content type="html" xml:base="https://yangjava.github.io/2022/11/08/Pyspark%E5%AE%9E%E6%88%98/">&lt;h1 id=&quot;pyspark实战&quot;&gt;PySpark实战&lt;/h1&gt;
&lt;p&gt;Python PySpark是Spark官方提供的一个Python类库，其中内置了完全的Spark API，使得Python用户在导入这个类库后，可以使用自己熟悉的Python语言来编写Spark应用程序，并最终将程序提交到Spark集群运行。&lt;/p&gt;

&lt;h1 id=&quot;window本地环境pyspark安装&quot;&gt;window本地环境PySpark安装&lt;/h1&gt;
&lt;p&gt;PySpark是基于Python语言开发的类库，仅支持在单机环境下供Python用户开发调试使用，需要将程序提交到Spark集群上才能使用Spark集群分布式的能力处理大规模的数据处理任务。&lt;/p&gt;

&lt;p&gt;PySpark就是官方为了让Python用户更方便地使用Spark而开发出来的类库。Python用户不需要编写复杂的底层逻辑，只需要调用PySpark的API即可。&lt;/p&gt;

&lt;p&gt;本文基于Windows 64位操作系统进行PySpark的安装演示。
现在主流的方式都是通过Anaconda来管理自己的Python环境了。安装PySpark&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;pip  pyspark 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;搭建Spark环境。我们从官网或者国内镜像下载最新版本的Spark安装包，这里下载的是spark-3.3.2-bin-hadoop3.tgz，然后将其解压缩到合适的位置，这里比如是D:\spark。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;https://mirrors.tuna.tsinghua.edu.cn/apache/spark/spark-3.3.2/
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;然后我们需要新增一个环境变量：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;SPARK_HOME=D:\spark\spark-3.3.2-bin-hadoop3
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;再将其添加到Path环境变量中：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;%SPARK_HOME%\bin
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;然后我们在命令行尝试运行spark\bin下面的pyspark：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt; pyspark
Python 3.10.9 | packaged by Anaconda, Inc. | (main, Mar  1 2023, 18:18:15) [MSC v.1916 64 bit (AMD64)] on win32
Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.
23/04/19 15:31:10 WARN Shell: Did not find winutils.exe: java.io.FileNotFoundException: java.io.FileNotFoundException: HADOOP_HOME and hadoop.home.dir are unset. -see https://wiki.apache.org/hadoop/WindowsProblems
Setting default log level to &quot;WARN&quot;.
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
23/04/19 15:31:10 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 3.3.2
      /_/

Using Python version 3.10.9 (main, Mar  1 2023 18:18:15)
Spark context Web UI available at http://DESKTOP-DFA24F11:4040
Spark context available as 'sc' (master = local[*], app id = local-1681889472795).
SparkSession available as 'spark'.
&amp;gt;&amp;gt;&amp;gt; 23/04/19 15:31:28 WARN ProcfsMetricsGetter: Exception when trying to compute pagesize, as a result reporting of ProcessTree metrics is stopped
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Hadoop环境搭建。由于Spark的运行需要Hadoop作为底层支持，所以我们还需要从官网或者国内镜像下载最新的Hadoop安装包，这里现在的是hadoop-3.3.4.tar.gz，然后将其加压缩到合适的目录，假设这里为D:\hadoop。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;然后我们需要配置Hadoop的环境变量，新建：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;HADOOP_HOME=D:\hadoop\hadoop-3.3.4
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;然后将其添加到Path环境变量中：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;%HADOOP_HOME%\bin
%HADOOP_HOME%\sbin
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;然后我们进入到D:\hadoop\hadoop-3.3.4\etc\hadoop目录下，修改hadoop-env.cmd，设置Java Home：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;set JAVA_HOME=C:\PROGRA~1\Java\jdk1.8.0_341
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;我本机的Java环境在C:\Program Files\Java，因为Program Files中间有空格，按照这样填写的话Hadoop启动会报错，无法找到Java的地址，因此我们使用PROGRA~1来代替Program Files就能解决这个问题。&lt;/p&gt;

&lt;p&gt;然后我们从github的winutils仓库中下载hadoop-3.0.0的压缩包，将其中的内容全部覆盖复制到D:\hadoop\hadoop-3.3.4\bin下面，然后将hadoop.dll拷贝到C:\Windows\System32下面，然后我们就可以验证Hadoop了：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;（base）PS C:\Users\zhangxun&amp;gt; hadoop version
Hadoop 3.3.4
Source code repository https://github.com/apache/hadoop.git -r a585a73c3e02ac62350c136643a5e7f6095a3dbb
Compiled by stevel on 2022-07-29T12:32Z
Compiled with protoc 3.7.1
From source with checksum fb9dd8918a7b8a5b430d61af858f6ec
This command was run using /D:/hadoop/hadoop-3.3.4/share/hadoop/common/hadoop-common-3.3.4.jar
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;至此，Hadoop配置完成。&lt;/p&gt;

&lt;h2 id=&quot;helloworld测试&quot;&gt;HelloWorld测试&lt;/h2&gt;
&lt;p&gt;我们在合适的地方新建一个文件夹，然后用vscode打开这个文件夹，后面的示例代码程序都在这个文件夹里面完成了。&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pyspark&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;SparkConf&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pyspark&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;SparkContext&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__name__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'__main__'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;conf&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SparkConf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setAppName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;test1&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setMaster&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;local&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SparkContext&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conf&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;rdd&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parallelize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;rdd是:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rdd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;rdd.collect是：&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rdd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;collect&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;执行该程序：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;gt;python hello.py
Setting default log level to &quot;WARN&quot;.
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
rdd是: ParallelCollectionRDD[0] at readRDDFromFile at PythonRDD.scala:274
rdd.collect是： [1, 2, 3, 4, 5]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;如此证明pyspark程序可以提交到本地的spark环境正常运行。&lt;/p&gt;

&lt;h2 id=&quot;pyspark程序运行机制分析&quot;&gt;PySpark程序运行机制分析&lt;/h2&gt;
&lt;p&gt;在没有学习PySpark执行原理之前，很多人可能会认为PySpark编写的程序会被翻译为JVM能识别的字节码，然后提交给Spark运行，其实不是这样的。&lt;/p&gt;

&lt;p&gt;Spark工作原理如下:
Driver负责总体的调度，Executor负责具体Task的运行，它们都是运行在JVM进程之中的，而这些JVM进程则是可以部署在多种的资源管理系统中的，比如Yarn、Mesos或者是K8s等；用户提交的Spark程序交给Driver进行管理，Driver将程序分解为一个个的Task交给Executor执行。&lt;/p&gt;

&lt;p&gt;为了不影响现有Spark的工作架构，Spark在外围包装了一层Python的API，借助Py4j实现Python和Java的交互，进而实现通过Python代码来编写Spark应用程序并提交给Spark集群运行。&lt;/p&gt;

&lt;p&gt;在Driver端，Python通过Py4j来调用Java方法，将用户使用Python写的程序映射到JVM中，比如，用户在PySpark中实例化一个Python的SparkContext对象，最终会在JVM中实例化Scala的SparkContext对象。&lt;/p&gt;

&lt;p&gt;在Executor端，都启动一个Python守护进程，当Task收到任务请求后，交给底层的Python进程去执行。&lt;/p&gt;

&lt;p&gt;所以，Pyspark的运行机制和我们预想的并不一样，这种方式可以不破坏现有的Spark执行架构，同时也方便多种语言支持的扩展，但是也很明显，使用PySpark运行Spark任务肯定比使用Java或者Scala要有一些额外的性能损耗。&lt;/p&gt;

&lt;h2 id=&quot;docker下安装pyspark&quot;&gt;Docker下安装PySpark&lt;/h2&gt;</content><author><name>杨京京</name></author><category term="Python" /><summary type="html">PySpark实战 Python PySpark是Spark官方提供的一个Python类库，其中内置了完全的Spark API，使得Python用户在导入这个类库后，可以使用自己熟悉的Python语言来编写Spark应用程序，并最终将程序提交到Spark集群运行。</summary></entry><entry><title type="html">微电影大导演</title><link href="https://yangjava.github.io/2022/11/07/%E5%BE%AE%E7%94%B5%E5%BD%B1%E5%A4%A7%E5%AF%BC%E6%BC%94/" rel="alternate" type="text/html" title="微电影大导演" /><published>2022-11-07T00:00:00+00:00</published><updated>2022-11-07T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/07/%E5%BE%AE%E7%94%B5%E5%BD%B1%E5%A4%A7%E5%AF%BC%E6%BC%94</id><content type="html" xml:base="https://yangjava.github.io/2022/11/07/%E5%BE%AE%E7%94%B5%E5%BD%B1%E5%A4%A7%E5%AF%BC%E6%BC%94/">&lt;p&gt;#&lt;/p&gt;</content><author><name>杨京京</name></author><category term="Shot" /><summary type="html">#</summary></entry><entry><title type="html">Pr剪辑视频</title><link href="https://yangjava.github.io/2022/11/06/PR%E5%89%AA%E8%BE%91%E8%A7%86%E9%A2%91/" rel="alternate" type="text/html" title="Pr剪辑视频" /><published>2022-11-06T00:00:00+00:00</published><updated>2022-11-06T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/06/PR%E5%89%AA%E8%BE%91%E8%A7%86%E9%A2%91</id><content type="html" xml:base="https://yangjava.github.io/2022/11/06/PR%E5%89%AA%E8%BE%91%E8%A7%86%E9%A2%91/">&lt;h1 id=&quot;pr剪辑视频&quot;&gt;PR剪辑视频&lt;/h1&gt;
&lt;p&gt;Pr全称Adobe Premiere,是Adobe公司开发的一款视频剪辑&amp;amp;编辑软件。主要用于视频采集、视频剪辑、调色、添加字幕、编辑音频、渲染输出。Pr是一款是功能强大、简单易学、应用面广、专业稳定的视频剪辑软件。&lt;/p&gt;

&lt;p&gt;##
帧：构成动画的最小单位，即组成动画的每一幅静态画面，一帧就是一幅静态画面。
帧速率：是视频中每秒包含的帧数，即每秒钟所播放的画面达到的数量。PAL制式影片（中国、德国、英国等采用的电视制式）的帧速率是25帧/秒，NTSC制式影片（美国、日本等采用的电视制式）的帧速度是29.97帧/秒，电影的帧速率是24帧/秒，二维动画的帧速率是12帧/秒。
场：在电视上，每一帧都有两个画面，电视机通过隔行扫描技术，把电视中的每个帧画面隔行抽掉一半，然后交错合成为一个帧的大小。由隔行扫描技术产生的两个画面被称为“场”。&lt;/p&gt;

&lt;h2 id=&quot;常用视频尺寸&quot;&gt;常用视频尺寸：&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;标清：标清是指标准清晰度视频，就制式而言，PAL制式标清视频尺寸为720像素×576像素。&lt;/li&gt;
  &lt;li&gt;高清：高于标清标准的视频被称为“高清视频”，如1280像素×720像素（也称“小高清”）、1920像素×1080像素（标准的高清视频尺寸，也称“全高清”）等。&lt;/li&gt;
  &lt;li&gt;2K：2K分辨率是指屏幕或者内容的水平分辨率达约2000像素的分辨率等级，标准的2K分辨率为2048像素×1080像素。&lt;/li&gt;
  &lt;li&gt;4K：K分辨率是指屏幕的物理分辨率达3840像素×2160像素，且能接收、解码、显示相应分辨率视频信号的电视。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;景别&quot;&gt;景别&lt;/h2&gt;
&lt;p&gt;景别是指由于在焦距一定时，摄影机与被摄体的距离不同，而造成被摄体在摄影机录像器中所呈现出的范围大小的区别，大致分为:远景、全景、中景、近景、特写。
景别组接类型：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;前进式：全景+中景+近景+特写&lt;/li&gt;
  &lt;li&gt;后退式：特写+近景+中景+全景&lt;/li&gt;
  &lt;li&gt;同等式：相同景别组接&lt;/li&gt;
  &lt;li&gt;两级式：跨度大的景别组接到一起&lt;/li&gt;
  &lt;li&gt;循环式：前进式和后退式的结合&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;剪辑工作流程&quot;&gt;剪辑工作流程&lt;/h2&gt;
&lt;p&gt;剪辑工作流程：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;素材导入。提前将准备好的素材（视频、音频、图片）分类放在文件夹中，然后导入pr。&lt;/li&gt;
  &lt;li&gt;素材编辑。素材编辑就是设置素材的入点与出点，以选择最合适的部分，然后按脚本组接不同素材的过程。&lt;/li&gt;
  &lt;li&gt;特技处理。对于视频素材，特技处理包括转场、特效、合成、叠加。对于音频素材，特技处理包括转场、特效。令人震撼的画面效果，就是经过特技处理产生的。&lt;/li&gt;
  &lt;li&gt;字幕制作。字幕是视频中非常重要的部分，它包括文字和图形两个方面。&lt;/li&gt;
  &lt;li&gt;输出与生成。视频编辑完成后，就可以生成视频文件，发布到网上。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;pr界面&quot;&gt;pr界面&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;项目面板 ：素材文件的管理者，将素材导入“项目”面板后，会在“项目”面板中显示素材的名称、帧速率、长度等信息。&lt;/li&gt;
  &lt;li&gt;素材预览窗口 ：用来查看时间线上的当前序列。&lt;/li&gt;
  &lt;li&gt;工具箱 ：其中的工具都是用来编辑素材文件的。&lt;/li&gt;
  &lt;li&gt;预设面板 ：包含很多种关于工作界面各个区域分布的预设，初期学习时，建议选择编辑模式，它是一种常用的预设面板。&lt;/li&gt;
  &lt;li&gt;效果控件面板 ：用来编辑各类效果的属性。&lt;/li&gt;
  &lt;li&gt;时间线 ：即时间轴，默认有3个视频轨道+3个音频轨道+1个主声道。视频轨道与ps一样有层级覆盖的特点。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;pr工具&quot;&gt;pr工具&lt;/h2&gt;
&lt;ul&gt;
  &lt;li&gt;选择工具 ：快捷键为V，可以用来选择素材、移动素材、调整素材等。+shift键可选择或者取消选择时间线上不连续的多个素材。+alt键可以单独选择在链接状态下的视频或音频，进行操作。+alt键拖曳素材，可以在时间线上复制该素材。先拖曳素材再按住Ctrl键，鼠标指针会变成向右的箭头，被拖曳的素材前端会有一排小三角，松开鼠标左键，素材将插入时间线上，原有素材向右顺延。&lt;/li&gt;
  &lt;li&gt;向前选择轨道工具组 ：向前选择轨道工具的快捷键为A，向后选择轨道工具的快捷键为Shift+A。当时间线上素材量较多、剪辑时长较长的时候，这两个工具可以选择所有的素材并进行整体调整。&lt;/li&gt;
  &lt;li&gt;波纹编辑工具 ：快捷键为B，单击素材的出点或者入点，鼠标指针会变成黄色的箭头，左右拖动素材增加或减少画面。&lt;/li&gt;
  &lt;li&gt;滚动编辑工具 ：快捷键为N，它与波纹编辑工具的区别是会同时选择编辑点左侧素材的出点和右侧素材的入点，在调节两个素材的长短，修改画面内容的时候，会使时间线的整个时长保持不变，也不会改变其他素材的时长。&lt;/li&gt;
  &lt;li&gt;比率拉伸工具 ：快捷键为R，它可以调整素材的速度以匹配时间线上空出来的波纹，相当于给素材做变速效果，当然它更多的时候是用于填补波纹空隙或者让画面与音乐节奏点相匹配，和“剪辑速度/持续时间”对话框的作用是一样的，不过在“剪辑速度/持续时间”对话框中，是要修改参数才能更改素材速度的，当不知道要修改多少参数才能填补空隙的时候，还是用比率拉伸工具比较合适。&lt;/li&gt;
  &lt;li&gt;剃刀工具 ：快捷键为C，选择剃刀工具后，鼠标指针会变成小刀片的形状，可以把素材一分为二，为素材添加编辑点。使用快捷键Ctrl+K可以根据播放头指针位置切割素材，与剃刀工具的作用是一样的。&lt;/li&gt;
  &lt;li&gt;外滑/内滑工具 ：外滑快捷键为Y，内滑快捷键为U。当使用外滑工具单击素材，并左右拖动画面时，可以改变素材的入点和出点，而不改变该素材在轨道中的位置和长度。外滑工具改变的是该素材的画面内容，相当于重新定义素材的入点和出点。&lt;/li&gt;
  &lt;li&gt;钢笔工具 ：快捷键为P，钢笔工具可以调整画面的运动路径、制作蒙版和添加关键帧。&lt;/li&gt;
  &lt;li&gt;手形工具 ：快捷键为H，选择手形工具，在时间线上单击轨道并左右拖动，可以左右移动时间线。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;项目创建及素材基本处理&quot;&gt;项目创建及素材基本处理&lt;/h2&gt;
&lt;p&gt;启动软件，出现欢迎使用界面，点击新建项目：修改名称和文件保存位置，其他不用修改，即创建好了一个项目。&lt;/p&gt;

&lt;p&gt;素材编辑的前提是必须要有序列，序列的大小决定了输出视频的尺寸大小。常用预设是HDV 720p25，其中720p25 指的是分辨率 1280×720，每秒播放25帧画面。&lt;/p&gt;</content><author><name>杨京京</name></author><category term="Shot" /><summary type="html">PR剪辑视频 Pr全称Adobe Premiere,是Adobe公司开发的一款视频剪辑&amp;amp;编辑软件。主要用于视频采集、视频剪辑、调色、添加字幕、编辑音频、渲染输出。Pr是一款是功能强大、简单易学、应用面广、专业稳定的视频剪辑软件。</summary></entry><entry><title type="html">Vue基础入门</title><link href="https://yangjava.github.io/2022/11/05/Vue%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8/" rel="alternate" type="text/html" title="Vue基础入门" /><published>2022-11-05T00:00:00+00:00</published><updated>2022-11-05T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/05/Vue%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8</id><content type="html" xml:base="https://yangjava.github.io/2022/11/05/Vue%E5%9F%BA%E7%A1%80%E5%85%A5%E9%97%A8/">&lt;h1 id=&quot;vue基础入门&quot;&gt;Vue基础入门&lt;/h1&gt;</content><author><name>杨京京</name></author><category term="JavaScript" /><category term="Vue" /><summary type="html">Vue基础入门</summary></entry><entry><title type="html">规则引擎实战</title><link href="https://yangjava.github.io/2022/11/02/%E8%A7%84%E5%88%99%E5%BC%95%E6%93%8E%E5%AE%9E%E6%88%98/" rel="alternate" type="text/html" title="规则引擎实战" /><published>2022-11-02T00:00:00+00:00</published><updated>2022-11-02T00:00:00+00:00</updated><id>https://yangjava.github.io/2022/11/02/%E8%A7%84%E5%88%99%E5%BC%95%E6%93%8E%E5%AE%9E%E6%88%98</id><content type="html" xml:base="https://yangjava.github.io/2022/11/02/%E8%A7%84%E5%88%99%E5%BC%95%E6%93%8E%E5%AE%9E%E6%88%98/">&lt;h1 id=&quot;drools-规则引擎实战&quot;&gt;Drools 规则引擎实战&lt;/h1&gt;

&lt;h2 id=&quot;drools常见的使用场景&quot;&gt;Drools常见的使用场景&lt;/h2&gt;
&lt;p&gt;Drools是一个规则引擎，通常用于实现业务规则管理和自动决策。下面是Drools常见的使用场景：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;客户端决策：Drools可以被用来处理客户端决策问题，如客户经理决策、客户评分卡、授信决策、风险评估等。&lt;/li&gt;
  &lt;li&gt;规则管理：Drools可以作为一个独立的规则管理平台，帮助企业管理规则和流程。&lt;/li&gt;
  &lt;li&gt;基于规则的业务流程管理：Drools可以集成到业务流程管理系统中，帮助企业管理规则驱动的业务流程。&lt;/li&gt;
  &lt;li&gt;数据验证和清洗：Drools可以被用来对数据进行验证和清洗，以确保数据的准确性和一致性。&lt;/li&gt;
  &lt;li&gt;基于事件的决策：Drools可以被用来实现基于事件的决策，如基于实时事件的促销决策、实时交易监测等。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;数据验证和清洗&quot;&gt;数据验证和清洗&lt;/h2&gt;
&lt;p&gt;Drools可以在数据验证和清洗场景中使用，通过使用规则来验证数据的有效性和一致性。具体来说，Drools可以用于：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;数据格式验证：可以使用Drools验证数据是否符合特定的格式要求，如邮件地址、电话号码等。&lt;/li&gt;
  &lt;li&gt;数据范围验证：可以使用Drools验证数据是否在允许的范围内，如年龄范围、工资范围等。&lt;/li&gt;
  &lt;li&gt;数据一致性验证：可以使用Drools验证不同数据项之间的一致性，如邮寄地址和电话号码的一致性等。&lt;/li&gt;
  &lt;li&gt;数据清洗：可以使用Drools对数据进行清洗，如删除重复的数据、修正错误的数据等。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;通过使用Drools进行数据验证和清洗，可以保证数据的准确性和一致性，从而提高数据的可靠性和可用性。&lt;/p&gt;

&lt;p&gt;如下几个规则是关于Drools在数据清洗场景中的示例&lt;/p&gt;

&lt;p&gt;删除重复的数据&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;rule &quot;Remove duplicate records&quot;
when
    $record1: Record( $id1: id, $name1: name, $age1: age, $email1: email )
    $record2: Record( id == $id1, name == $name1, age == $age1, email == $email1 )
    $record1 != $record2
then
    retract( $record2 );
end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;修正错误的数据&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;rule &quot;Correct invalid email addresses&quot;
when
    $record: Record( email not matches &quot;(\\w+\\.)*\\w+@\\w+\\.\\w+&quot; )
then
    modify( $record ) { setEmail( &quot;invalid&quot; ) };
end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;数据格式转换 使用Drools对数据进行格式转换，如将日期字段从  一种格式转换为另一种格式等。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;package com.example.drools.rules;

import com.example.drools.DataCleaningExample.Record;

rule &quot;Remove Records with Invalid Age&quot;
when
    $record : Record(age &amp;lt; 0 || age &amp;gt; 120)
then
    retract($record);
end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;上面的规则演示了标准化地址的功能（将所有地址字段转换为大写字母）。&lt;/p&gt;

&lt;p&gt;去除噪声数据 使用Drools对数据进行预处理，如去除数据中的噪声等。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;package com.example.drools.rules;

import com.example.drools.DataCleaningExample.Record;

rule &quot;Remove Outliers - Age&quot;
when
    $record : Record(age &amp;lt; 18 || age &amp;gt; 65)
then
    retract($record);
end

rule &quot;Remove Outliers - Address&quot;
when
    $record : Record(address matches &quot;.*[0-9].*&quot;)
then
    retract($record);
end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;这是两个Drools规则，分别演示了如何删除年龄的离群值（年龄小于18或大于65）和地址的离群值（地址中包含数字）。&lt;/p&gt;

&lt;p&gt;填补缺失的数据 Drools对数据进行预处理，如填补缺失的数据等。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;package com.example.drools.rules;

import com.example.drools.DataCleaningExample.Record;

rule &quot;Fill Missing Name&quot;
when
    $record : Record(name == null || name.isEmpty())
then
    $record.setName(&quot;N/A&quot;);
end

rule &quot;Fill Missing Age&quot;
when
    $record : Record(age == 0)
then
    $record.setAge(30);
end

rule &quot;Fill Missing Address&quot;
when
    $record : Record(address == null || address.isEmpty())
then
    $record.setAddress(&quot;N/A&quot;);
end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;这是三个Drools规则，分别演示了如何填补缺失的名称，年龄和地址。&lt;/p&gt;

&lt;h2 id=&quot;客户评分卡&quot;&gt;客户评分卡&lt;/h2&gt;
&lt;p&gt;Drools可以用于客户评分卡场景，以评估客户的信用评分。它可以通过评估客户的财务历史、信用历史和个人信息等因素来评分客户。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;package com.example.drools.rules;

import com.example.drools.CreditScoringExample.Customer;

rule &quot;Good Credit History&quot;
when
$customer : Customer(creditHistory == &quot;Good&quot;)
then
$customer.setScore($customer.getScore() + 20);
end

rule &quot;High Income&quot;
when
$customer : Customer(income &amp;gt; 75000)
then
$customer.setScore($customer.getScore() + 10);
end

rule &quot;Long Employment&quot;
when
$customer : Customer(employmentLength &amp;gt; 5)
then
$customer.setScore($customer.getScore() + 15);
end

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;基于规则的业务流程管理&quot;&gt;基于规则的业务流程管理&lt;/h2&gt;
&lt;p&gt;Drools可以用于帮助企业管理规则和流程。它可以作为一种途径，帮助企业管理和自动化各种业务规则，如：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;权限管理：判断用户是否具有某种特定的权限，以访问特定的功能或数据。&lt;/li&gt;
  &lt;li&gt;工作流管理：帮助企业管理复杂的业务流程，如请求审批或订单处理。&lt;/li&gt;
  &lt;li&gt;报价管理：帮助企业根据特定的规则，计算客户的报价。&lt;/li&gt;
  &lt;li&gt;优惠券管理：帮助企业判断特定的优惠券是否适用于特定的客户。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;如下是一个简单的Drools规则示例，演示了如何管理报价：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;package com.example.drools.rules;

import com.example.drools.PricingManagementExample.Order;

rule &quot;Discount for High Volume Orders&quot;
when
    $order : Order(quantity &amp;gt; 100)
then
    $order.setDiscount(0.10);
end

rule &quot;Discount for Repeat Customers&quot;
when
    $order : Order(customer.numberOfOrders &amp;gt; 10)
then
    $order.setDiscount(0.05);
end

rule &quot;Discount for Large Orders&quot;
when
    $order : Order(total &amp;gt; 1000)
then
    $order.setDiscount(0.15);
end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;这是三个Drools规则，分别演示了如何为大量订单、重复顾客和大订单提供折扣。&lt;/p&gt;

&lt;h2 id=&quot;基于事件的决策&quot;&gt;基于事件的决策&lt;/h2&gt;
&lt;p&gt;Drools可以通过使用事件驱动的决策来实现基于事件的决策。它通过监听事件并触发相应的规则来实现事件驱动的决策。规则可以根据事件中包含的信息执行特定的操作，如：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;审批请求：当客户发起请求时，根据请求类型和客户信息执行相应的审批操作。&lt;/li&gt;
  &lt;li&gt;发送通知：当特定事件发生时，发送通知到相关的人员或系统。&lt;/li&gt;
  &lt;li&gt;执行操作：当特定事件发生时，执行特定的操作，如修改数据或发送请求。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;如下是一个简单的Drools规则示例，演示了如何执行基于事件的决策：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;package com.example.drools.rules;

import com.example.drools.EventDrivenDecisionMakingExample.OrderEvent;

rule &quot;Approve High Volume Orders&quot;
when
    $orderEvent : OrderEvent(order.quantity &amp;gt; 100)
then
    $orderEvent.getOrder().setApproved(true);
end

rule &quot;Send Notification for Large Orders&quot;
when
    $orderEvent : OrderEvent(order.total &amp;gt; 1000)
then
    // Send notification to relevant personnel or system
end

rule &quot;Update Inventory for Approved Orders&quot;
when
    $orderEvent : OrderEvent(order.isApproved() == true)
then
    // Update inventory information
end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;这是三个Drools规则，分别演示了如何批准大量订单、发送通知和更新库存信息。&lt;/p&gt;

&lt;h2 id=&quot;银行业务审批&quot;&gt;银行业务审批&lt;/h2&gt;
&lt;p&gt;在银行业务审批中，Drools可以应用于贷款审批和信用卡审批等场景。通过规则引擎，银行可以根据客户的贷款申请和信用历史等信息，自动化地判断是否批准贷款或信用卡。&lt;/p&gt;

&lt;p&gt;下面是一个简单的银行业务审批案例，演示了Drools如何在银行业务审批中使用：&lt;/p&gt;

&lt;p&gt;规则文件（loan-approval.drl）&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;package rules;

import org.dtt.entity.*;

rule &quot;Reject Loan for Applicant with Bad Credit Score&quot;
when
  $applicant:Applicant(creditScore &amp;lt; 600)
  $loanApplication:LoanApplication(applicant == $applicant)
then
  $loanApplication.setApproved(false);
  $loanApplication.setReason(&quot;Rejected due to low credit score&quot;);
  System.out.println(&quot;Rejected due to low credit score&quot;);
  retract($loanApplication);
end

rule &quot;Approve Loan for Applicant with Good Credit Score&quot;
when
  $applicant:Applicant(creditScore &amp;gt;= 600)
  $loanApplication:LoanApplication(applicant == $applicant)
then
  $loanApplication.setApproved(true);
  $loanApplication.setReason(&quot;Approved&quot;);
  System.out.println(&quot;Approve Loan for Applicant with Good Credit Score --&amp;gt; approved&quot;);
end

rule &quot;Reject Loan for Applicant with Low Income&quot;
when
  $applicant:Applicant(income &amp;lt; 5000)
  $loanApplication:LoanApplication(applicant == $applicant)
then
  $loanApplication.setApproved(false);
  $loanApplication.setReason(&quot;Rejected due to low income&quot;);
  retract($loanApplication);
  System.out.println(&quot;Reject Loan for Applicant with Low Income --&amp;gt; reject&quot;);
end


rule &quot;print&quot;
when
  $loanApplication: LoanApplication()
then
  System.out.println($loanApplication.getApplicant().getName());
end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Fact类&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import java.io.Serializable;
public class Applicant implements Serializable {
    private String name;
    private int age;
    private int creditScore;
    private double income;
    public LoanApplication(Applicant applicant, Integer loanAmount) {
        this.applicant = applicant;
        this.loanAmount = loanAmount;
    }
//省略Getters/Setters方法
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public class LoanApplication {
   private Applicant applicant;
    private Integer loanAmount;
    private boolean approved;
    private String reason;
	//省略Getters/Setters方法
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;测试示例
在我们运行TestLoanApproval代码时，它会触发Drools规则引擎，并使用LoanApplication和Applicant对象作为规则的输入。Drools规则引擎将按照定义的规则来评估这些对象，并决定是否批准贷款申请。&lt;/p&gt;

&lt;p&gt;如果所有的规则都被评估为true，那么贷款申请将被批准。在这种情况下，LoanApprovalTest中的断言语句将不会抛出任何异常，代表测试成功。&lt;/p&gt;

&lt;p&gt;如果任何一个规则评估为false，那么贷款申请将不会被批准。在这种情况下，LoanApprovalTest中的断言语句将抛出异常，代表测试失败。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; @Test
public void testLoanApproval() {
    KieServices kieServices = KieServices.Factory.get();
    KieContainer kieContainer = kieServices.newKieClasspathContainer();
    KieSession kieSession = kieContainer.newKieSession();
    Applicant applicant = new Applicant(&quot;Joe&quot;, 23, 900, 10000);
    LoanApplication loanApplication = new LoanApplication(applicant);
    loanApplication.setLoanAmount(100000);
    kieSession.insert(applicant);
    kieSession.insert(loanApplication);
    kieSession.fireAllRules();
    kieSession.dispose();
    assertTrue(loanApplication.isApproved());
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;小明喝汽水问题&quot;&gt;小明喝汽水问题&lt;/h2&gt;
&lt;p&gt;1元钱一瓶汽水，喝完后两个空瓶换一瓶汽水，问：小明有20元钱，最多可以喝到几瓶汽水？&lt;/p&gt;

&lt;p&gt;规则拆分
规则1：1元钱一瓶汽水–&amp;gt; 有钱就买水，空瓶+1，钱-1，喝水+1
规则2：两个空瓶换一瓶汽水–&amp;gt;有空瓶就换钱，空瓶-2，钱+1&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;//规则1：1元钱一瓶汽水。有钱就买水，空瓶+1，钱-1，喝水+1；
        rule &quot;rule1&quot;
            salience 3
            when
                $m:XiaoMing(money&amp;gt;0);
            then
                System.out.println(&quot;有钱即可喝水，钱：&quot;+$m.getMoney());
                $m.setBottle($m.getBottle()+1);
                $m.setMoney($m.getMoney()-1);
                $m.setDrink($m.getDrink()+1);
                update($m)
        end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;需要注意的是，如果想要换水，需要再编写一个规则，描述空瓶的变化情况。&lt;/p&gt;

&lt;p&gt;该规则描述了：当XiaoMing实例的bottle属性大于等于2时，空瓶减少2瓶，喝水量增加1瓶，并且更新XiaoMing实例。&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;//规则2：两个空瓶换一瓶汽水。有空瓶就换钱，空瓶-2，钱+1；
        rule &quot;rule2&quot;
            salience 2
            when
                $m:XiaoMing(bottle&amp;gt;=2);
            then
                System.out.println(&quot;有瓶子就换钱，瓶子：&quot;+$m.getBottle());
                $m.setBottle($m.getBottle()-2);
                $m.setMoney($m.getMoney()+1);
                update($m)
        end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;如果想要在Drools规则中打印喝水数量，可以在合适的地方添加一行代码，例如在最终状态打印喝水数量：&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;//规则3，当XiaoMing实例的money属性小于等于0时，打印喝水数量
        rule &quot;rule3&quot;
            salience 1
            when
                $m:XiaoMing(money&amp;lt;=0);
            then
                System.out.println(&quot;总共喝掉：&quot;+$m.getDrink());
        end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Fact类&lt;/p&gt;
&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/**
 * Fact定义
 */&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;XiaoMing&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;//总共的钱&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;money&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;//空瓶子数目&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bottle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;//已经喝掉的汽水&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;drink&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;
	&lt;span class=&quot;c1&quot;&gt;//省略getters、setters方法.....&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;测试方法&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;@Test
public void test01() {
        KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();
        System.out.println(kc.verify().getMessages().toString());
        KieSession ksession = kc.newKieSession(&quot;mingKS&quot;);
        XiaoMing xiaoMing=new XiaoMing();
        xiaoMing.setMoney(20);
        ksession.insert(xiaoMing);
        ksession.fireAllRules();
        ksession.dispose();
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;高尔夫球员站位问题&quot;&gt;高尔夫球员站位问题&lt;/h2&gt;
&lt;p&gt;问题分析
已知有四个高尔夫球员，他们的名字是Fred,Joe,Bob,Tom；今天他们分别穿着红色，蓝色，橙色，以及格子衣服，并且他们按照从左往右的顺序站成一排。我们将最左边的位置定为1，最右边的位置定为4，中间依次是2,3位置。&lt;/p&gt;

&lt;p&gt;现在我们了解的情况是：&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;高尔夫球员Fred,目前不知道他的位置和衣服颜色&lt;/li&gt;
  &lt;li&gt;Fred右边紧挨着的球员穿蓝色衣服&lt;/li&gt;
  &lt;li&gt;Joe排在第2个位置&lt;/li&gt;
  &lt;li&gt;Bob穿着格子短裤&lt;/li&gt;
  &lt;li&gt;Tom没有排在第1位或第4位，也没有穿橙色衣服
请问,这四名球员的位置和衣服颜色。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;规则&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;package com.xshe.drools

import com.xshe.drools.bean.Golfer;

rule &quot;find solution&quot;
    when
        //1.高尔夫球员Fred,目前不知道他的位置和衣服颜色
        $fred : Golfer( name == &quot;Fred&quot; )

        //3.Joe排在第2个位置
        $joe : Golfer( name == &quot;Joe&quot;,
                position == 2,
                position != $fred.position,
                color != $fred.color )

        //4.Bob穿着格子短裤
        $bob : Golfer( name == &quot;Bob&quot;,
                position != $fred.position,
                position != $joe.position,
                color == &quot;plaid&quot;,
                color != $fred.color,
                color != $joe.color )

        //5.Tom没有排在第1位或第4位，也没有穿橙色衣服
        $tom : Golfer( name == &quot;Tom&quot;,
                position != 1,
                position != 4,
                position != $fred.position,
                position != $joe.position,
                position != $bob.position,
                color != &quot;orange&quot;,
                color != $fred.color,
                color != $joe.color,
                color != $bob.color )

        //2.Fred右边紧挨着的球员穿蓝色衣服
        Golfer( position == ( $fred.position + 1 ),
                      color == &quot;blue&quot;,
                      this in ( $joe, $bob, $tom ) )

    then
        System.out.println( &quot;Fred &quot; + $fred.getPosition() + &quot; &quot; + $fred.getColor() );
        System.out.println( &quot;Joe &quot; + $joe.getPosition() + &quot; &quot; + $joe.getColor() );
        System.out.println( &quot;Bob &quot; + $bob.getPosition() + &quot; &quot; + $bob.getColor() );
        System.out.println( &quot;Tom &quot; + $tom.getPosition() + &quot; &quot; + $tom.getColor() );
end
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;测试&quot;&gt;测试&lt;/h2&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;public static void main(final String[] args) {
        KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();
        System.out.println(kc.verify().getMessages().toString());
        KieSession ksession = kc.newKieSession(&quot;golfKS&quot;);
        String[] names = new String[]{&quot;Fred&quot;, &quot;Joe&quot;, &quot;Bob&quot;, &quot;Tom&quot;};
        String[] colors = new String[]{&quot;red&quot;, &quot;blue&quot;, &quot;plaid&quot;, &quot;orange&quot;};
        int[] positions = new int[]{1, 2, 3, 4};

        for (String name : names) {
            for (String color : colors) {
                for (int position : positions) {
                    ksession.insert(new Golfer(name, color, position));
                }
            }
        }
        ksession.fireAllRules();
        ksession.dispose();
    }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;springboot规则引擎来实现打折&quot;&gt;SpringBoot规则引擎来实现打折&lt;/h2&gt;
&lt;p&gt;现在有这么个需求，网上购物，需要根据不同的规则计算商品折扣，比如VIP客户增加5%的折扣，购买金额超过1000元的增加10%的折扣等，而且这些规则可能随时发生变化，甚至增加新的规则。面对这个需求，你该怎么实现呢？难道是计算规则一变，就要修改业务代码，重新测试，上线吗。&lt;/p&gt;

&lt;h3 id=&quot;引入依赖&quot;&gt;引入依赖&lt;/h3&gt;
&lt;p&gt;我们创建一个spring boot应用程序，pom中添加drools相关的依赖，如下：&lt;/p&gt;
&lt;div class=&quot;language-xml highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nt&quot;&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;  
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.drools&lt;span class=&quot;nt&quot;&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;  
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;drools-core&lt;span class=&quot;nt&quot;&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;  
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;version&amp;gt;&lt;/span&gt;7.59.0.Final&lt;span class=&quot;nt&quot;&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;  
&lt;span class=&quot;nt&quot;&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;  
&lt;span class=&quot;nt&quot;&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;  
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.drools&lt;span class=&quot;nt&quot;&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;  
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;drools-compiler&lt;span class=&quot;nt&quot;&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;  
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;version&amp;gt;&lt;/span&gt;7.59.0.Final&lt;span class=&quot;nt&quot;&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;  
&lt;span class=&quot;nt&quot;&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;  
&lt;span class=&quot;nt&quot;&gt;&amp;lt;dependency&amp;gt;&lt;/span&gt;  
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;groupId&amp;gt;&lt;/span&gt;org.drools&lt;span class=&quot;nt&quot;&gt;&amp;lt;/groupId&amp;gt;&lt;/span&gt;  
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;artifactId&amp;gt;&lt;/span&gt;drools-decisiontables&lt;span class=&quot;nt&quot;&gt;&amp;lt;/artifactId&amp;gt;&lt;/span&gt;  
  &lt;span class=&quot;nt&quot;&gt;&amp;lt;version&amp;gt;&lt;/span&gt;7.59.0.Final&lt;span class=&quot;nt&quot;&gt;&amp;lt;/version&amp;gt;&lt;/span&gt;  
&lt;span class=&quot;nt&quot;&gt;&amp;lt;/dependency&amp;gt;&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;drools配置类&quot;&gt;Drools配置类&lt;/h3&gt;
&lt;p&gt;创建一个名为DroolsConfig的配置 java 类。&lt;/p&gt;
&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nd&quot;&gt;@Configuration&lt;/span&gt;  
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DroolsConfig&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;  
    &lt;span class=&quot;c1&quot;&gt;// 制定规则文件的路径  &lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;RULES_CUSTOMER_RULES_DRL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;rules/customer-discount.drl&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;static&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;KieServices&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieServices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;KieServices&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;Factory&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;  
  
    &lt;span class=&quot;nd&quot;&gt;@Bean&lt;/span&gt;  
    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;KieContainer&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;kieContainer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;  
        &lt;span class=&quot;nc&quot;&gt;KieFileSystem&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieFileSystem&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieServices&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;newKieFileSystem&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;  
        &lt;span class=&quot;n&quot;&gt;kieFileSystem&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;write&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ResourceFactory&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;newClassPathResource&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;RULES_CUSTOMER_RULES_DRL&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;));&lt;/span&gt;  
        &lt;span class=&quot;nc&quot;&gt;KieBuilder&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieServices&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;newKieBuilder&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kieFileSystem&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  
        &lt;span class=&quot;n&quot;&gt;kb&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;buildAll&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;  
        &lt;span class=&quot;nc&quot;&gt;KieModule&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieModule&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kb&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getKieModule&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;  
        &lt;span class=&quot;nc&quot;&gt;KieContainer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieContainer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieServices&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;newKieContainer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kieModule&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;getReleaseId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;());&lt;/span&gt;  
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieContainer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;  
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;ul&gt;
  &lt;li&gt;定义了一个 KieContainer的Spring Bean ，KieContainer用于通过加载应用程序的/resources文件夹下的规则文件来构建规则引擎。&lt;/li&gt;
  &lt;li&gt;创建KieFileSystem实例并配置规则引擎并从应用程序的资源目录加载规则的 DRL 文件。&lt;/li&gt;
  &lt;li&gt;使用KieBuilder实例来构建 drools 模块。我们可以使用KieSerive单例实例来创建 KieBuilder 实例。&lt;/li&gt;
  &lt;li&gt;最后，使用 KieService 创建一个 KieContainer 并将其配置为 spring bean。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;添加业务model&quot;&gt;添加业务Model&lt;/h2&gt;
&lt;p&gt;创建一个订单对象OrderRequest，这个类中的字段后续回作为输入信息发送给定义的drools规则中，用来计算给定客户订单的折扣金额。&lt;/p&gt;
&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nd&quot;&gt;@Getter&lt;/span&gt;  
&lt;span class=&quot;nd&quot;&gt;@Setter&lt;/span&gt;  
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;OrderRequest&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;  
    &lt;span class=&quot;cm&quot;&gt;/**  
     * 客户号  
     */&lt;/span&gt;  
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;customerNumber&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
    &lt;span class=&quot;cm&quot;&gt;/**  
     * 年龄  
     */&lt;/span&gt;  
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
    &lt;span class=&quot;cm&quot;&gt;/**  
     * 订单金额  
     */&lt;/span&gt;  
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;amount&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
    &lt;span class=&quot;cm&quot;&gt;/**  
     * 客户类型  
     */&lt;/span&gt;  
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CustomerType&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;customerType&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;此外，定义一个客户类型CustomerType 的枚举，规则引擎会根据该值计算客户订单折扣百分比，如下所示。&lt;/p&gt;
&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;enum&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CustomerType&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;  
    &lt;span class=&quot;no&quot;&gt;LOYAL&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;NEW&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;DISSATISFIED&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
  
    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;getValue&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;  
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;toString&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;  
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;  
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;最后，创建一个订单折扣类 OrderDiscount ，用来表示计算得到的最终的折扣，如下所示。&lt;/p&gt;
&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nd&quot;&gt;@Getter&lt;/span&gt;  
&lt;span class=&quot;nd&quot;&gt;@Setter&lt;/span&gt;  
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;OrderDiscount&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;  
  
    &lt;span class=&quot;cm&quot;&gt;/**  
     * 折扣  
     */&lt;/span&gt;  
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Integer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;discount&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;我们将使用上述响应对象返回计算出的折扣。&lt;/p&gt;

&lt;h3 id=&quot;定义drools-规则&quot;&gt;定义drools 规则&lt;/h3&gt;
&lt;p&gt;前面的DroolsConfig类中指定drools规则的目录，现在我们在/src/main/resources/rules目录下添加customer- discount.drl文件，在里面定义对应的规则。&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; import com.alvin.drools.model.OrderRequest;  
import com.alvin.drools.model.CustomerType;  
global com.alvin.drools.model.OrderDiscount orderDiscount;  
  
dialect &quot;mvel&quot;  
  
// 规则1: 根据年龄判断  
rule &quot;Age based discount&quot;  
    when  
        // 当客户年龄在20岁以下或者50岁以上  
        OrderRequest(age &amp;lt; 20 || age &amp;gt; 50)  
    then  
        // 则添加10%的折扣  
        System.out.println(&quot;==========Adding 10% discount for Kids/ senior customer=============&quot;);  
        orderDiscount.setDiscount(orderDiscount.getDiscount() + 10);  
end  
  
// 规则2： 根据客户类型的规则  
rule &quot;Customer type based discount - Loyal customer&quot;  
    when  
        // 当客户类型是LOYAL  
        OrderRequest(customerType.getValue == &quot;LOYAL&quot;)  
    then  
        // 则增加5%的折扣  
        System.out.println(&quot;==========Adding 5% discount for LOYAL customer=============&quot;);  
        orderDiscount.setDiscount(orderDiscount.getDiscount() + 5);  
end  
  
rule &quot;Customer type based discount - others&quot;  
    when  
    OrderRequest(customerType.getValue != &quot;LOYAL&quot;)  
then  
    System.out.println(&quot;==========Adding 3% discount for NEW or DISSATISFIED customer=============&quot;);  
    orderDiscount.setDiscount(orderDiscount.getDiscount() + 3);  
end  
  
rule &quot;Amount based discount&quot;  
    when  
        OrderRequest(amount &amp;gt; 1000L)  
    then  
        System.out.println(&quot;==========Adding 5% discount for amount more than 1000$=============&quot;);  
    orderDiscount.setDiscount(orderDiscount.getDiscount() + 5);  
end  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;这个drl文件虽然不是java文件，但还是很容易看懂的。&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;我们使用了一个名为orderDiscount 的全局参数，可以在多个规则之间共享。&lt;/li&gt;
  &lt;li&gt;drl 文件可以包含一个或多个规则。我们可以使用mvel语法来指定规则。此外，每个规则使用rule关键字进行描述。&lt;/li&gt;
  &lt;li&gt;每个规则when-then语法来定义规则的条件。&lt;/li&gt;
  &lt;li&gt;根据订单请求的输入值，我们正在为结果添加折扣。如果规则表达式匹配，每个规则都会向全局结果变量添加额外的折扣。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;添加service层&quot;&gt;添加Service层&lt;/h2&gt;
&lt;p&gt;创建一个名为OrderDiscountService 的服务类，如下：&lt;/p&gt;
&lt;div class=&quot;language-java highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nd&quot;&gt;@Service&lt;/span&gt;  
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;OrderDiscountService&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;  
  
    &lt;span class=&quot;nd&quot;&gt;@Autowired&lt;/span&gt;  
    &lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;KieContainer&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieContainer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
  
    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;OrderDiscount&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;getDiscount&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;OrderRequest&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orderRequest&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;{&lt;/span&gt;  
        &lt;span class=&quot;nc&quot;&gt;OrderDiscount&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orderDiscount&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;OrderDiscount&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;  
        &lt;span class=&quot;c1&quot;&gt;// 开启会话  &lt;/span&gt;
        &lt;span class=&quot;nc&quot;&gt;KieSession&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieSession&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kieContainer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;newKieSession&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;  
        &lt;span class=&quot;c1&quot;&gt;// 设置折扣对象  &lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kieSession&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;setGlobal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;orderDiscount&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orderDiscount&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  
        &lt;span class=&quot;c1&quot;&gt;// 设置订单对象  &lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kieSession&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;insert&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orderRequest&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;);&lt;/span&gt;  
        &lt;span class=&quot;c1&quot;&gt;// 触发规则  &lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kieSession&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;fireAllRules&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;  
        &lt;span class=&quot;c1&quot;&gt;// 中止会话  &lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kieSession&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;na&quot;&gt;dispose&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;();&lt;/span&gt;  
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orderDiscount&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;;&lt;/span&gt;  
    &lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;  
&lt;span class=&quot;o&quot;&gt;}&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;ul&gt;
  &lt;li&gt;注入KieContainer实例并创建一个KieSession实例。&lt;/li&gt;
  &lt;li&gt;设置了一个OrderDiscount类型的全局参数，它将保存规则执行结果。&lt;/li&gt;
  &lt;li&gt;使用insert()方法将请求对象传递给 drl 文件。&lt;/li&gt;
  &lt;li&gt;调用fireAllRules()方法触发所有规则。&lt;/li&gt;
  &lt;li&gt;最后通过调用KieSession 的dispose()方法终止会话。&lt;/li&gt;
&lt;/ul&gt;</content><author><name>杨京京</name></author><category term="Drools" /><category term="Rules" /><summary type="html">Drools 规则引擎实战</summary></entry></feed>