├── LICENSE
├── README.md
├── READMEIMG
├── 211690962797_.pic.jpg
├── Project-Name.png
├── image(1).png
└── image(2).png
├── pom.xml
└── src
└── main
├── java
└── com
│ └── gch
│ └── discount
│ ├── core
│ ├── aware
│ │ └── CalculatorRouter.java
│ ├── discount
│ │ ├── Calculator.java
│ │ └── impl
│ │ │ └── AbstractCalculator.java
│ ├── enums
│ │ └── GroupRelation.java
│ ├── model
│ │ ├── common
│ │ │ ├── CalcResult.java
│ │ │ ├── CalcStage.java
│ │ │ ├── CalcState.java
│ │ │ ├── DiscountConfig.java
│ │ │ ├── DiscountContext.java
│ │ │ ├── DiscountGroup.java
│ │ │ ├── DiscountWrapper.java
│ │ │ └── Item.java
│ │ └── goods
│ │ │ ├── GoodsInfo.java
│ │ │ └── GoodsItem.java
│ ├── permutation
│ │ └── Permutation.java
│ ├── precompute
│ │ ├── PreCompute.java
│ │ └── PreComputeHolder.java
│ └── utils
│ │ ├── DiscountGroupUtil.java
│ │ ├── IdGenerator.java
│ │ └── LimitingUtil.java
│ └── demo
│ ├── App.java
│ └── biz
│ ├── Flowable.java
│ ├── TestController.java
│ ├── calc
│ ├── ManjianCalc.java
│ └── ZhekouCalc.java
│ ├── constant
│ └── Constant.java
│ └── precompute
│ └── PreGroupBy.java
└── resources
└── calculator-core.properties
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |

3 |
4 |
5 |
6 |
12 |
13 |
14 | ## 轻量级算法驱动优惠叠加器
15 |
16 | #### RT:
17 |
18 |
19 |
20 | #### 背景:
21 |
22 | 优惠是推动消费者转化的关键因素,它在激发用户消费行为上起着核心作用。目前市场上的优惠策略主要涵盖了各种活动(例如拼多多的“砍一刀”,天猫农场的互动,新用户的首次购买,复购,积分等)和优惠券(如折扣券,代金券,商品券,买一赠一等)。然而,这些复杂的优惠规则使得用户在计算优惠叠加的顺序时感到困扰。这可能导致用户在面对多重优惠时降低购买商品的欲望,尤其是当他们参与了多个活动并持有多个优惠券时,这种情况更为明显。
23 |
24 | 优惠的计算顺序可以分为平行式和渐进式,其中平行式优惠之间没有相互依赖关系,而渐进式优惠之间则存在依赖关系,即下一个优惠的触发取决于上一个优惠的实施结果。
25 |
26 | 设想小晴消费了100元,她手头有一张7折优惠券和一张满100元减30元的优惠券。这两个优惠券的使用顺序可能会产生不同的效果,则这2个优惠券的使用顺序有以下两种情况:
27 |
28 |
29 |
30 | `OnePRO`采用了一系列新颖的算法,实现了高效求解优惠排列的最优解。
31 |
32 |
33 |
34 | #### 核心计算类 Permutation<T extends GoodsItem>
35 |
36 | `Permutation`是一个重要的抽象类,作为`OnePRO`的核心,它采用了多种优化策略来确保高性能,这些策略的运用旨在提升计算效率和降低资源消耗,这些策略包括:
37 |
38 | - 预存的排列数结果集
39 |
40 | 之所以采用这种设计,是因为在业务场景中,我们需要频繁进行排列计算。对于给定长度的序列,其排列结果是固定的。在`Permutation`类中,`PERMUTATIONS`属性存储了7以内的排列数结果集。由于这里使用了`Byte`来存储数据,因此占用的内存空间非常小,这有助于提高性能并降低内存消耗。
41 |
42 | ```Java
43 | private final static Map>> PERMUTATIONS = Maps.newHashMap();
44 |
45 | ```
46 | 这个动作在类加载完成时执行,如果觉得7不合适,对7不满意,可以通过调整`SUPPORTEDSIZE`的大小来满足业务和性能的需求。
47 |
48 | 我们在实现中经过测试和调整,确定了7是一个相对平衡的参数,它兼顾了业务与性能,当然,根据实际需求,大家可以根据自己的情况来调整这个参数。
49 |
50 | ```Java
51 | public final static int SUPPORTEDSIZE = 7;
52 |
53 | static{
54 | //前置计算 1-SUPPORTEDSIZE 之间所有排列组合
55 | for(byte i=1;i<=SUPPORTEDSIZE;i++){
56 | PERMUTATIONS.put((int)i,Collections2.permutations(IntStream.range(0,i).boxed().map(x->(byte)x.intValue()).collect(Collectors.toList())));
57 | }
58 | }
59 |
60 | ```
61 |
62 | - $A_n^3$级别缓存
63 |
64 | 相对于传统的`Key-Value`结构,解决 $A_n^n$问题的缓存需要进行特殊设计,对于一个优惠集合而言, $A_n^3$意味着需要缓存*n*×(*n*−1)×(*n*−2)条数据。当n=7时,需要缓存210条数据。为了在内存大小和缓存带来的性能收益之间取得平衡, $A_n^3$是最合适的级别。
65 |
66 | `Permutation`类通过其成员变量`cache`实现了高性能缓存。
67 |
68 | ```Java
69 | private final Map> cache = Maps.newHashMap();
70 | ```
71 | 你或许已经注意到,`cache`的键值使用的是`Integer`类型。在大多数情况下,我们更倾向于使用`String`类型,但在需要进行大量计算的场景中,比如在万次计算的场景下,String字符串的拼接却成了性能瓶颈。
72 |
73 | 为了实现高性能的键生成,`Permutation`采用了独特的方法。它通过位移对`Byte`数组的前三个字节进行扰动,以确保每个键的唯一性,同时提升性能。
74 |
75 | ```Java
76 | private static Integer calcKey(List a){
77 | return a.size()>=3?(a.get(0) << 6)+ (a.get(1) << 3) + a.get(2):0;
78 | }
79 | ```
80 |
81 | `Permutation`提供了保存点来实现 $A_n^3$ 级别缓存,`CalcState` 记录了计算到第3步的状态,包括当前订单优惠金额和计算过程、已享用优惠的商品等,这些属性的保存和回放`Permutation`已经帮你做好了,`Permutation`额外提供了抽象的保存和回放方法来满足你的个性化诉求。
82 |
83 | ```Java
84 | /**
85 | * 业务将状态记录到保存点
86 | * @param state 保存点对象
87 | */
88 | protected abstract void makeSnapshot(CalcState state,DiscountContext context);
89 |
90 | /**
91 | * 业务返回保存点状态
92 | * @param state 保存点对象
93 | */
94 | protected abstract void backToSnapshot(CalcState state,DiscountContext context);
95 | ```
96 |
97 | 在优惠计算中,存在一个优先级规则,即优惠计算是有优先级的,需要确保属性`calculateGroup`值较小的优惠先行计算。当发生`backToSnapshot`时,我们需要额外检查缓存中最后一个优惠与当前正准备要计算的优惠之间的关系,如果不满足特定条件,则直接终止计算,直接跳出。而`checkIfWakeUpJump`方法会在缓存被使用后立即判断是否需要继续下去。
98 |
99 | #### 上下文类 DiscountContext<T extends GoodsItem>
100 |
101 | `DiscountContext`是上下文,也是`Permutation`的成员变量,`DiscountContext`同样包含很多优化策略:
102 |
103 | - CalcStage数组
104 |
105 | 在变更最频繁也是最重要的计算步骤对象`CalcStage`使用数组存储,该数组随着上下文创建而创建,在`Permutation`中使用
106 |
107 | ```Java
108 | Arrays.fill(arr,null);
109 | ```
110 |
111 | 将该数组清空并让它投入下一次计算,这样一次全排列过程中,数组只会被创建一次,避免了频繁创建数组带来的性能损耗。
112 |
113 | - 预计算
114 |
115 | `DiscountContext`的初始化是通过静态的`create`方法完成的,该方法将商品与优惠绑定在一起,同时执行一些用户自定义的逻辑,我们称之为“预计算”,预计算的结果被保存在`DiscountContext`的`preCompute`属性中,以便在后续的计算中直接取用,这种方法避免了在后续的高速迭代中重复执行相同的操作,如商品分组和、求和等,从而提高了计算效率。
116 |
117 | #### 预计算 PreCompute<T extends GoodsItem>
118 |
119 | 预计算提供了接口,要使用预计算首先需要实现PreCompute接口
120 |
121 | ```Java
122 | public interface PreCompute {
123 | /**
124 | * 判断符合条件的活动类型,符合才会执行preComputeItems
125 | */
126 | Set matchTypes();
127 |
128 | /**
129 | * 对商品做一些复杂集合操作
130 | * @param items 当前参与优惠的商品
131 | * @param discount 当前优惠
132 | * @param preCompute 存储计算的结果
133 | */
134 | void preComputeItems(List items, DiscountWrapper discount, Map preCompute);
135 | }
136 | ```
137 |
138 | 此外需要在资源目录下建立`calculator-core.properties`文件,配置内容如下
139 |
140 | ```Java
141 | precompute.path=你要扫描的包
142 | ```
143 | `PreComputeHolder`将处理所有的`PreCompute`实现类,只有`matchTypes`匹配的情况下,才会执行`preComputeItems`方法。
144 |
145 | ```Java
146 | public class PreComputeHolder {
147 | public static Set COMPUTES= Sets.newHashSet();
148 | private final static String PATH = "precompute.path";
149 |
150 | static{
151 | Properties properties = new Properties();
152 | try {
153 | properties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(Objects.requireNonNull(PreComputeHolder.class.getClassLoader().getResource("calculator-core.properties")).getPath()));
154 | } catch (Exception ignore) {
155 | }
156 | String path = properties.getProperty(PATH);
157 | if(StringUtils.isNotBlank(path)){
158 | Reflections reflections = new Reflections(path);
159 | Set> subTypes = reflections.getSubTypesOf(PreCompute.class);
160 | for(Class extends PreCompute> clazz:subTypes){
161 | try {
162 | COMPUTES.add(clazz.newInstance());
163 | } catch (Exception ignore) {
164 | }
165 | }
166 | }
167 | }
168 | }
169 | ```
170 |
171 | #### 计算器 Calculator
172 |
173 | `Calculator`是单个优惠的计算接口(即用于优惠计算的接口),它其中定义了一个`calcWarp`方法,负责具体的优惠计算逻辑,但由于`calcWarp`需要承担一些内部的事情,需要处理一些内部细节,因此为了简化使用者的开发工作,我们提供了一个抽象类`AbstractCalculator`,它实现了`calcWarp`方法,并最终暴露了一个更简单更直观的`calc`方法供使用者使用。
174 |
175 | `AbstractCalculator`的内容如下,在`AbstractCalculator`中,`calcWarp`方法负责创建`CalcStage`对象,维护`CalcStage`数组等内部工作,这些细节对于使用者来说是透明的,他们只需要关注并实现`calc`方法即可。
176 |
177 | ```Java
178 | public abstract class AbstractCalculator implements Calculator {
179 | public long calcWarp(DiscountContext context, DiscountWrapper discountWrapper, Map records, byte idx, int i) {
180 | CalcStage stage = new CalcStage();
181 | CalcResult cr = context.getCalcResult();
182 | long price= cr.getCurPrice();
183 | stage.setBeforeCalcPrice(price);
184 | price = calc(context, discountWrapper,records, price, stage);
185 | if(price<0){
186 | return price;
187 | }
188 | stage.setAfterCalcPrice(price);
189 | stage.setIndex(idx);
190 | stage.setStageType(discountWrapper.getType());
191 | cr.setCurPrice(price);
192 | if(stage.getBeforeCalcPrice()>stage.getAfterCalcPrice()) {
193 | cr.getCurStages()[i] = stage;
194 | }
195 | return price;
196 | }
197 |
198 | /**
199 | * 返回该优惠下的最终要支付的金额,若不符合则返回 prevStagePrice
200 | * @param context 上下文
201 | * @param discountWrapper 优惠信息
202 | * @param records 记录享受过优惠的单品,key是calculateId,这里只提供容器,添加和判断规则由使用者自行决定
203 | * @param prevStagePrice 上一步计算的订单的价格
204 | * @param curStage 当前stage
205 | * @return
206 | */
207 | public abstract long calc(DiscountContext context, DiscountWrapper discountWrapper, Map records, long prevStagePrice, CalcStage curStage);
208 |
209 | }
210 |
211 | ```
212 | 最终用户通过继承`AbstractCalculator`类,并在`Component`注解中指定一个值,而`CalculatorRouter`则通过这个值将请求路由到相应的优惠计算器,这个值与`DiscountWrapper`中的`type`属性相对应。
213 |
214 | ```Java
215 | @Component("manjian")
216 | public class ManjianCalc extends AbstractCalculator {
217 | ......
218 | }
219 | ```
220 |
221 |
222 | #### 共享互斥协议 DiscountGroup
223 |
224 | 共享互斥协议是一个数据结构,它是一个数组,数组中最多可以包含两个对象,最少包含一个对象。如果数组中只有一个对象,那么该对象必然为共享组,即组内的优惠可以叠加使用。
225 |
226 | ```JavaScript
227 | [
228 | {
229 | "relation": "share",
230 | "items":
231 | [
232 | {
233 | "type": "activity0",
234 | "id": "11"
235 | }
236 | ,
237 | {
238 | "type": "activity4",
239 | "id": "13"
240 | }
241 | ,
242 | {
243 | "type": "coupon1",
244 | "id": "14"
245 | }
246 | ]
247 | }]
248 | ```
249 | 相应的,当数组中包含两个对象时,第一个对象的`relation`属性可以为`share`或`exclude`,而第二个对象的`relation`属性必须为`exclude`。
250 |
251 | ```JavaScript
252 | [
253 | {
254 | "relation": "share",
255 | "items":
256 | [
257 | {
258 | "type": "activity0",
259 | "id": "11"
260 | },
261 | {
262 | "type": "card3",
263 | "id":"12"
264 | }
265 | ]
266 | },
267 | {
268 | "relation": "exclude",
269 | "items":
270 | [
271 | {
272 | "type": "card1",
273 | "id": "18"
274 | },
275 | {
276 | "type": "coupon1",
277 | "id": "22"
278 | }
279 | ]
280 | }
281 | ]
282 | ```
283 | 最终,上述协议将转化为如下两个共享组:
284 |
285 | - `activity0-card3-card1` 和 `activity0-card3-coupon1`
286 |
287 | 工具类 `DiscountGroupUtil` 提供了一个方法,用于将协议转换为共享组。由于共享组可能包含大量优惠,为了提高过滤性能,我们将当前可用的优惠转换为二级`Map`。这个`Map`的外层键是协议中的`type`,而第二层键是协议中的`id`。通过这种方式,我们可以快速地进行交叉过滤,从而提升性能。
288 |
289 | ```Java
290 | public static List,Set>> transform(List> groups, Map> inMap);
291 | ```
292 | 为了确保计算性能,我们将用户在当前订单中可享受的优惠分为两个集合。左侧集合的大小限制为`SUPPORTEDSIZE`,即我们重点保障的、在计算能力范围内的优惠。而右侧集合则尽可能地进行叠加。
293 |
294 | 从稳定性角度考虑,我们需要对计算次数进行统计。在压力测试中,我们通过`LimitingUtil.count`方法来统计进入`calc`方法的次数。显然,在没有开启缓存的情况下,计算次数为 $A_n^n$×n,而当开启缓存时,计算次数为 $A_n^n$×(n−3)+ $A_n^3$。
295 |
296 | #### CASE
297 |
298 | 看了这么多概念,我们可以在`com.gch.discount.demo`包中找到实际调用的具体case:
299 |
300 | ```Java
301 | @Controller
302 | public class TestController {
303 |
304 | private final CalculatorRouter calculatorRouter;
305 |
306 | public TestController(CalculatorRouter calculatorRouter) {
307 | this.calculatorRouter = calculatorRouter;
308 | }
309 |
310 | @RequestMapping("test")
311 | @ResponseBody
312 | public Object test() {
313 | //mock商品
314 | List items = mockItems();
315 | //mock组关系并转化为共享组
316 | List,Set>> pairs = transform(mockGroups());
317 | //全局最优计算过程
318 | List globalStages=Lists.newArrayList();
319 | int count = 0;
320 | //订单总金额
321 | long totalPrice = items.stream().mapToLong(GoodsInfo::getSalePrice).sum();
322 | long globalPrice = totalPrice;
323 | //构建计算流
324 | Flowable flowable = (Flowable) new Flowable().build(calculatorRouter);
325 | for(Pair,Set> set:pairs) {
326 | //统计算力
327 | count += LimitingUtil.count(set.getLeft().size());
328 | if(count>N){
329 | break;
330 | }
331 | List wrappers = Lists.newArrayList(set.getLeft());
332 | DiscountContext ctx = DiscountContext.create(totalPrice, Lists.newArrayList(items), wrappers);
333 | flowable.perm(ctx);
334 | if(ctx.getCalcResult().getFinalPrice() < globalPrice) {
335 | globalStages = Arrays.asList(ctx.getCalcResult().getStages());
336 | globalPrice = ctx.getCalcResult().getFinalPrice();
337 | }
338 | }
339 | return Pair.of(globalPrice,globalStages);
340 | }
341 |
342 | private List> mockGroups(){
343 | List> groups = Lists.newArrayList();
344 | DiscountGroup group = new DiscountGroup();
345 | group.setRelation(GroupRelation.SHARE.getType());
346 | group.setItems(Lists.newArrayList(new Item("zhekou","1"),new Item("manjian","2"),new Item("manzeng","3")));
347 | groups.add(Lists.newArrayList(group));
348 | return groups;
349 | }
350 |
351 | private List mockItems(){
352 | IdGenerator idGenerator = IdGenerator.getInstance();
353 | GoodsInfo goodsInfo = GoodsInfo.of(1001L,2001L,null,4,20 * 100,"产品1",null);
354 | GoodsInfo goodsInfo2 = GoodsInfo.of(1001L,2002L,null,2,10 * 100,"产品1",null);
355 | List items = GoodsItem.generateItems(goodsInfo,idGenerator,x->x.getExtra().put(Constant.UPDATEABLEPRICE,x.getSalePrice()));
356 | items.addAll(GoodsItem.generateItems(goodsInfo2,idGenerator,x->x.getExtra().put(Constant.UPDATEABLEPRICE,x.getSalePrice())));
357 | return items;
358 | }
359 |
360 | private List,Set>> transform(List> groups){
361 | List wrapperList = Lists.newArrayList(
362 | DiscountWrapper.of("zhekou", "1", "折扣", false, new DiscountConfig()),
363 | DiscountWrapper.of("manjian", "2", "满减", false, new DiscountConfig())
364 | );
365 | Map> inMap = wrapperList.stream().collect(Collectors.toMap(DiscountWrapper::getType, x->ImmutableMap.of(x.getId(),x)));
366 | return DiscountGroupUtil.transform(groups,inMap);
367 | }
368 | }
369 |
370 | ```
371 |
372 |
373 |
374 |
375 |
376 |
--------------------------------------------------------------------------------
/READMEIMG/211690962797_.pic.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GaoSSR/OnePRO/c7aac1eb3ea695cba74b4bc0cfc6d19feca93a6f/READMEIMG/211690962797_.pic.jpg
--------------------------------------------------------------------------------
/READMEIMG/Project-Name.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GaoSSR/OnePRO/c7aac1eb3ea695cba74b4bc0cfc6d19feca93a6f/READMEIMG/Project-Name.png
--------------------------------------------------------------------------------
/READMEIMG/image(1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GaoSSR/OnePRO/c7aac1eb3ea695cba74b4bc0cfc6d19feca93a6f/READMEIMG/image(1).png
--------------------------------------------------------------------------------
/READMEIMG/image(2).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GaoSSR/OnePRO/c7aac1eb3ea695cba74b4bc0cfc6d19feca93a6f/READMEIMG/image(2).png
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 | com.gch
7 | 4.0.0
8 | jar
9 | OnePRO
10 | OnePRO
11 | 1.0-SNAPSHOT
12 |
13 |
14 | org.springframework.boot
15 | spring-boot-starter-parent
16 | 2.2.6.RELEASE
17 |
18 |
19 |
20 |
21 | UTF-8
22 | 1.8
23 | 1.8
24 |
25 |
26 |
27 |
28 | org.reflections
29 | reflections
30 | 0.10.2
31 |
32 |
33 | org.apache.commons
34 | commons-lang3
35 | 3.12.0
36 |
37 |
38 | com.alibaba
39 | fastjson
40 | 1.2.80
41 |
42 |
43 | org.apache.commons
44 | commons-collections4
45 | 4.4
46 |
47 |
48 | com.google.guava
49 | guava
50 | 31.1-jre
51 |
52 |
53 | org.projectlombok
54 | lombok
55 | 1.18.24
56 |
57 |
58 | org.springframework.boot
59 | spring-boot-starter-web
60 | 2.2.6.RELEASE
61 |
62 |
63 | org.springframework.boot
64 | spring-boot-starter-test
65 | 2.2.6.RELEASE
66 |
67 |
68 | net.logstash.logback
69 | logstash-logback-encoder
70 | 4.9
71 |
72 |
73 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/aware/CalculatorRouter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.aware;
18 |
19 | import com.gch.discount.core.discount.Calculator;
20 | import org.springframework.beans.BeansException;
21 | import org.springframework.context.ApplicationContext;
22 | import org.springframework.context.ApplicationContextAware;
23 | import org.springframework.stereotype.Component;
24 |
25 | import java.util.Map;
26 |
27 | /**
28 | * 根据注解路由到目标Calculator
29 | * @author: GaoSSR
30 | * @date: 2023/8
31 | */
32 | @Component
33 | @SuppressWarnings("all")
34 | public class CalculatorRouter implements ApplicationContextAware {
35 |
36 | private Map map;
37 |
38 | @Override
39 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
40 | map = applicationContext.getBeansOfType(Calculator.class);
41 | }
42 |
43 |
44 | public Map getMap() {
45 | return map;
46 | }
47 |
48 | public Calculator getService(String key) {
49 | return map.get(key);
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/discount/Calculator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.discount;
18 |
19 | import com.gch.discount.core.model.common.DiscountContext;
20 | import com.gch.discount.core.model.common.DiscountWrapper;
21 | import com.gch.discount.core.model.goods.GoodsItem;
22 |
23 | import java.util.Map;
24 |
25 | /**
26 | * 优惠计算器接口
27 | * @author: GaoSSR
28 | * @date: 2023/8
29 | */
30 | public interface Calculator {
31 |
32 | /**
33 | * 优惠计算引擎的内部方法
34 | * @param context 上下文
35 | * @param discountWrapper 当前优惠信息
36 | * @param records 参与优惠的商品记录,用于过滤
37 | * @param idx 活动的index
38 | * @param i 当前计算的索引下标,它和idx的区别在于比如有数组[9,4,6,5],则i为数组下标 i=1 时对应的idx是4
39 | */
40 | long calcWarp(DiscountContext context, DiscountWrapper discountWrapper, Map records, byte idx, int i);
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/discount/impl/AbstractCalculator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.discount.impl;
18 |
19 | import com.gch.discount.core.discount.Calculator;
20 | import com.gch.discount.core.model.common.*;
21 | import com.gch.discount.core.model.goods.GoodsItem;
22 |
23 | import java.util.Map;
24 |
25 | /**
26 | * 抽象计算器类,每种类型优惠做一个实现类,负责创建 stage,维护CalcStage[]数组等内部工作,这对使用者是透明的
27 | * @author: GaoSSR
28 | * @date: 2023/8
29 | */
30 | public abstract class AbstractCalculator implements Calculator {
31 |
32 | public long calcWarp(DiscountContext context, DiscountWrapper discountWrapper, Map records, byte idx, int i) {
33 | CalcStage stage = new CalcStage();
34 | CalcResult cr = context.getCalcResult();
35 | long price = cr.getCurPrice();
36 | stage.setBeforeCalcPrice(price);
37 | price = calc(context, discountWrapper, records, price, stage);
38 | if (price < 0) {
39 | return price;
40 | }
41 | stage.setAfterCalcPrice(price);
42 | stage.setIndex(idx);
43 | stage.setStageType(discountWrapper.getType());
44 | cr.setCurPrice(price);
45 | if (stage.getBeforeCalcPrice() > stage.getAfterCalcPrice()) {
46 | cr.getCurStages()[i] = stage;
47 | }
48 | return price;
49 | }
50 |
51 | /**
52 | * 返回该优惠下的最终要支付的金额,若不符合则返回 prevStagePrice
53 | * @param context 上下文
54 | * @param discountWrapper 优惠信息
55 | * @param records 记录享受过优惠的单品,key是calculateId,这里只提供容器,添加和判断规则由使用者自行决定
56 | * @param prevStagePrice 上一步计算出的订单的价格
57 | * @param curStage 当前stage
58 | * @return
59 | */
60 | public abstract long calc(DiscountContext context, DiscountWrapper discountWrapper, Map records, long prevStagePrice, CalcStage curStage);
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/enums/GroupRelation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.enums;
18 |
19 | /**
20 | * 组内关系枚举
21 | * 组内关系枚举
22 | * @author: GaoSSR
23 | * @date: 2023/8
24 | */
25 | public enum GroupRelation {
26 |
27 | SHARE("share"),
28 | EXCLUDE("exclude");
29 |
30 | private String type;
31 |
32 | GroupRelation(String type) {
33 | this.type = type;
34 | }
35 |
36 | public String getType() {
37 | return type;
38 | }
39 |
40 | public void setType(String type) {
41 | this.type = type;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/common/CalcResult.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.common;
18 |
19 | import com.fasterxml.jackson.annotation.JsonIgnore;
20 | import lombok.Data;
21 |
22 | import java.io.Serializable;
23 |
24 | /**
25 | * 优惠计算结果
26 | * @author: GaoSSR
27 | * @date: 2023/8
28 | */
29 | @Data
30 | public class CalcResult implements Serializable {
31 |
32 | private CalcResult() {
33 | }
34 |
35 | /**
36 | * 最优实付金额
37 | */
38 | private long finalPrice;
39 |
40 | /**
41 | * 最优优惠计算过程
42 | */
43 | private CalcStage[] stages;
44 |
45 | /**
46 | * 当前序列计算的实付金额
47 | */
48 | @JsonIgnore
49 | private transient long curFinalPrice;
50 |
51 | /**
52 | * 当前序列优惠计算过程
53 | */
54 | @JsonIgnore
55 | private transient CalcStage[] curStages;
56 |
57 | /**
58 | * 实时计算价格
59 | */
60 | @JsonIgnore
61 | private transient long curPrice;
62 |
63 | public static CalcResult create(int n) {
64 | CalcResult c = new CalcResult();
65 | c.stages = new CalcStage[n];
66 | c.curStages = new CalcStage[n];
67 | return c;
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/common/CalcStage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.common;
18 |
19 | import lombok.*;
20 |
21 | import java.io.Serializable;
22 | import java.util.Map;
23 |
24 | /**
25 | * 单个具体优惠计算明细,可以当成日志来用,用于计算过程的追溯
26 | * @author: GaoSSR
27 | * @date: 2023/8
28 | */
29 | @Data
30 | public class CalcStage implements Serializable {
31 |
32 | /**
33 | * 优惠前价格
34 | */
35 | private long beforeCalcPrice;
36 |
37 | /**
38 | * 优惠后价格
39 | */
40 | private long afterCalcPrice;
41 |
42 | /**
43 | * 优惠类型
44 | */
45 | private String stageType;
46 |
47 | /**
48 | * 优惠索引
49 | */
50 | private byte index;
51 |
52 | /**
53 | * 扩展属性
54 | */
55 | private Map extra;
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/common/CalcState.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.common;
18 |
19 | import com.gch.discount.core.model.goods.GoodsItem;
20 | import lombok.Data;
21 |
22 | import java.io.Serializable;
23 | import java.util.Map;
24 |
25 | /**
26 | * 保存点,用于缓存,入计算到第3个节点时可以将所有状态写入CalcState
27 | * @author: GaoSSR
28 | * @date: 2023/8
29 | */
30 | @Data
31 | public class CalcState implements Serializable {
32 |
33 | /**
34 | * 截止到保存点计算的最终优惠价格
35 | */
36 | private long curPrice;
37 |
38 | /**
39 | * 截止到保存点计算的CalcStage
40 | */
41 | private CalcStage[] curStages;
42 |
43 | /**
44 | * 截止到保存点的商品列表
45 | */
46 | private Map goodsItems;
47 |
48 | /**
49 | * 截止到保存点的已计算商品列表
50 | */
51 | private Map records;
52 |
53 | /**
54 | * 截止到保存点的扩展信息
55 | */
56 | private Map extra;
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/common/DiscountConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.common;
18 |
19 | import lombok.Data;
20 |
21 | import java.io.Serializable;
22 | import java.util.List;
23 | import java.util.Map;
24 |
25 | /**
26 | * 优惠配置信息
27 | * @author: GaoSSR
28 | * @date: 2023/7
29 | */
30 | @Data
31 | public class DiscountConfig implements Serializable {
32 |
33 | /**
34 | * 当前优惠的优先级(如10 - 单商品组, 20 - 整单组)
35 | */
36 | private int calculateGroup;
37 |
38 | /**
39 | * 商品限制 (0 - 所有商品可参与,1 - 指定某些商品参与, 2- 指定某些商品不参与)
40 | */
41 | private int goodsType;
42 |
43 | /**
44 | * 下一个属性 itemIds 存放的内容是啥,(0 - 商品ID, 1 - SKUID, 2 - 类目Id)
45 | */
46 | private int itemIdType;
47 |
48 | /**
49 | * 同上
50 | */
51 | private List itemIds;
52 |
53 | /**
54 | * 活动信息扩展信息
55 | */
56 | private Map extra;
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/common/DiscountContext.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.common;
18 |
19 | import com.gch.discount.core.model.goods.GoodsItem;
20 | import com.gch.discount.core.precompute.PreCompute;
21 | import com.gch.discount.core.precompute.PreComputeHolder;
22 | import com.google.common.collect.Lists;
23 | import com.google.common.collect.Maps;
24 | import lombok.Data;
25 | import org.apache.commons.collections4.CollectionUtils;
26 |
27 | import java.io.Serializable;
28 | import java.util.List;
29 | import java.util.Map;
30 | import java.util.stream.Collectors;
31 |
32 | /**
33 | * 优惠上下文,包含一些初始化工作、预计算等等
34 | * @author: GaoSSR
35 | * @date: 2023/8
36 | */
37 | @Data
38 | public class DiscountContext implements Serializable {
39 |
40 | private DiscountContext() {
41 | }
42 |
43 | /**
44 | * 原始价格
45 | */
46 | private long originalPrice;
47 |
48 | /**
49 | * 优惠的计算结果
50 | */
51 | private CalcResult calcResult;
52 |
53 |
54 | /**
55 | * 当前订单参与计算的商品
56 | */
57 | private List goodsItems;
58 |
59 | /**
60 | * 当前订单可用优惠的配置
61 | */
62 | private List discountWrappers;
63 |
64 | /**
65 | * 优惠维度进行商品分组,这样每个计算器只取自己相关的商品
66 | */
67 | private Map> discountItemGroup;
68 |
69 | /**
70 | * 记录享受过优惠的单品,key是calculateId
71 | */
72 | private Map records;
73 |
74 | /**
75 | * 存储预计算的结果
76 | */
77 | private Map preCompute;
78 |
79 | /**
80 | * 扩展字段
81 | */
82 | private Map extra;
83 |
84 |
85 | /**
86 | * 构造一个上下文
87 | *
88 | * @param originalPrice 订单原始价格
89 | * @param goodsItems 可用商品列表
90 | * @param discountWrappers 可用优惠列表
91 | * @return
92 | */
93 | public static DiscountContext create(long originalPrice, List goodsItems, List discountWrappers) {
94 | DiscountContext c = new DiscountContext<>();
95 | c.originalPrice = originalPrice;
96 | c.records = Maps.newHashMap();
97 | c.discountItemGroup = Maps.newHashMap();
98 | c.calcResult = CalcResult.create(discountWrappers.size());
99 | c.calcResult.setFinalPrice(originalPrice);
100 | c.goodsItems = goodsItems;
101 | c.discountWrappers = discountWrappers;
102 | c.preCompute = Maps.newHashMap();
103 | //预处理优惠
104 | for (DiscountWrapper discount : discountWrappers) {
105 | initDiscount(c, discount);
106 | }
107 | return c;
108 | }
109 |
110 |
111 | /**
112 | * 对某个优惠进行初始化工作,包括商品的筛选、预计算逻辑
113 | *
114 | * @param c 上下文
115 | * @param discount 当前优惠的信息
116 | */
117 | private static void initDiscount(DiscountContext c, DiscountWrapper discount) {
118 | DiscountConfig conf = discount.getDiscountConfig();
119 | List list = Lists.newArrayList(c.goodsItems);
120 | if (0 == conf.getGoodsType()) {
121 | //不限制
122 | list = list.stream().sorted().collect(Collectors.toList());
123 | c.discountItemGroup.put(discount.getId(), list);
124 | } else if (1 == conf.getGoodsType()) {
125 | if (0 == conf.getItemIdType()) {
126 | list = list.stream().filter(x -> conf.getItemIds().
127 | contains(x.getGoodsId())).sorted().collect(Collectors.toList());
128 | c.discountItemGroup.put(discount.getId(), list);
129 | } else if (1 == conf.getItemIdType()) {
130 | list = list.stream().filter(x -> conf.getItemIds().
131 | contains(x.getSkuId())).sorted().collect(Collectors.toList());
132 | c.discountItemGroup.put(discount.getId(), list);
133 | } else {
134 | list = list.stream().filter(x -> CollectionUtils.intersection(
135 | conf.getItemIds(), x.getCategoryIds()).size() > 0).sorted().collect(Collectors.toList());
136 | c.discountItemGroup.put(discount.getId(), list);
137 | }
138 | } else {
139 | //指定不参与
140 | if (0 == conf.getItemIdType()) {
141 | list = list.stream().filter(x -> !conf.getItemIds().
142 | contains(x.getGoodsId())).sorted().collect(Collectors.toList());
143 | c.discountItemGroup.put(discount.getId(), list);
144 | } else if (1 == conf.getItemIdType()) {
145 | list = list.stream().filter(x -> !conf.getItemIds().
146 | contains(x.getSkuId())).sorted().collect(Collectors.toList());
147 | c.discountItemGroup.put(discount.getId(), list);
148 | } else {
149 | list = list.stream().filter(x -> CollectionUtils.intersection(
150 | conf.getItemIds(), x.getCategoryIds()).size() == 0).sorted().collect(Collectors.toList());
151 | c.discountItemGroup.put(discount.getId(), list);
152 | }
153 | }
154 | runPreCompute(c, discount, list);
155 | }
156 |
157 | /**
158 | * 预计算
159 | *
160 | * @param c 上下文
161 | * @param discount 当前的优惠信息
162 | * @param list 当前优惠匹配的商品列表
163 | */
164 | @SuppressWarnings("unchecked")
165 | private static void runPreCompute(DiscountContext c, DiscountWrapper discount, List list) {
166 | list = Lists.newArrayList(list);
167 | for (PreCompute e : PreComputeHolder.COMPUTES) {
168 | if (e.matchTypes().contains(discount.getType())) {
169 | e.preComputeItems(list, discount, c.preCompute);
170 | }
171 | }
172 | }
173 |
174 | }
175 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/common/DiscountGroup.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.common;
18 |
19 | import com.google.common.collect.Lists;
20 | import lombok.*;
21 | import org.apache.commons.collections4.CollectionUtils;
22 | import org.apache.commons.collections4.MapUtils;
23 | import org.apache.commons.lang3.StringUtils;
24 |
25 | import java.io.Serializable;
26 | import java.util.Iterator;
27 | import java.util.List;
28 | import java.util.Map;
29 |
30 | /**
31 | * 共享互斥组
32 | * @author: GaoSSR
33 | * @date: 2023/8
34 | */
35 | @Data
36 | public class DiscountGroup implements Serializable {
37 |
38 | private String relation;
39 | private List- items;
40 |
41 | /**
42 | * 根据用户可用的优惠,对组内信息进行过滤
43 | * @param inMap
44 | * @return
45 | */
46 | public List
- filterItems(Map> inMap) {
47 | //inMap 外层key为type,内层key为id,value为DiscountWrapper
48 | if (CollectionUtils.isEmpty(items) || MapUtils.isEmpty(inMap)) {
49 | return null;
50 | }
51 | //构建items副本
52 | List
- itemsCopy = Lists.newArrayList(items);
53 | Iterator
- it = itemsCopy.iterator();
54 | while (it.hasNext()) {
55 | Item item = it.next();
56 | if (!inMap.containsKey(item.getType())) {
57 | it.remove();
58 | continue;
59 | }
60 | if (StringUtils.isNotBlank(item.getId())) {
61 | //理论上m不可能为空
62 | Map m = inMap.get(item.getType());
63 | if (MapUtils.isNotEmpty(m)) {
64 | if (!m.containsKey(item.getId())) {
65 | it.remove();
66 | }
67 | }
68 | }
69 | }
70 | return itemsCopy;
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/common/DiscountWrapper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.common;
18 |
19 | import lombok.Data;
20 |
21 | import java.io.Serializable;
22 | import java.util.Objects;
23 |
24 | /**
25 | * 优惠类
26 | * @author: GaoSSR
27 | * @date: 2023/7
28 | */
29 | @Data
30 | public class DiscountWrapper implements Serializable, Comparable {
31 |
32 | /**
33 | * 优惠的具体类型,CalculatorRouter会根据这个type在Calculator的实现类中扫描
34 | */
35 | private String type;
36 |
37 | /**
38 | * 优惠的ID
39 | */
40 | private String id;
41 |
42 | /**
43 | * 优惠的名称
44 | */
45 | private String name;
46 |
47 | /**
48 | * 是否是必须使用的优惠
49 | */
50 | private boolean mustUse;
51 |
52 | /**
53 | * 优惠的配置信息
54 | */
55 | private DiscountConfig discountConfig;
56 |
57 |
58 | public static DiscountWrapper of(String type, String id, String name, boolean mustUse, DiscountConfig discountConfig) {
59 | DiscountWrapper wrapper = new DiscountWrapper();
60 | wrapper.setType(type);
61 | wrapper.setId(id);
62 | wrapper.setName(name);
63 | wrapper.setMustUse(mustUse);
64 | wrapper.setDiscountConfig(discountConfig);
65 | return wrapper;
66 | }
67 |
68 | @Override
69 | public boolean equals(Object o) {
70 | if (this == o) return true;
71 | if (o == null || getClass() != o.getClass()) return false;
72 | DiscountWrapper wrapper = (DiscountWrapper) o;
73 | return type.equals(wrapper.type) && id.equals(wrapper.id);
74 | }
75 |
76 | @Override
77 | public int hashCode() {
78 | return Objects.hash(type, id);
79 | }
80 |
81 | @Override
82 | public int compareTo(DiscountWrapper o) {
83 | return (this.type + this.id).compareTo(o.getType() + o.getId());
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/common/Item.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.common;
18 |
19 | import lombok.*;
20 |
21 | import java.io.Serializable;
22 |
23 | /**
24 | * 共享互斥关系中的元素
25 | * @author: GaoSSR
26 | * @date: 2023/8
27 | */
28 | @AllArgsConstructor
29 | @NoArgsConstructor
30 | @Getter
31 | @Setter
32 | @ToString
33 | @EqualsAndHashCode
34 | public class Item implements Serializable {
35 | /**
36 | * 优惠类型,和DiscountWrapper中的type保持一致
37 | */
38 | private String type;
39 |
40 | /**
41 | * 优惠的ID,和DiscountWrapper中的id保持一致
42 | */
43 | private String id;
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/goods/GoodsInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.goods;
18 |
19 | import com.google.common.collect.Maps;
20 | import lombok.Data;
21 |
22 | import java.io.Serializable;
23 | import java.util.List;
24 | import java.util.Map;
25 |
26 | /**
27 | * 商品信息
28 | * @author: GaoSSR
29 | * @date: 2023/7
30 | */
31 | @Data
32 | public class GoodsInfo implements Serializable, Cloneable {
33 |
34 | /**
35 | * 商品ID
36 | */
37 | private Long goodsId;
38 |
39 | /**
40 | * 商品的SKUID
41 | */
42 | private Long skuId;
43 |
44 | /**
45 | * 商品分类ID,一个商品可能出现在多个品类中
46 | */
47 | private List categoryIds;
48 |
49 | /**
50 | * 购买数量
51 | */
52 | private int num;
53 |
54 | /**
55 | * 商品价格,用于计算(单位:分)
56 | */
57 | private long salePrice;
58 |
59 | /**
60 | * 商品名
61 | */
62 | private String name;
63 |
64 | /**
65 | * 商品扩展属性
66 | */
67 | private Map goodsExtra = Maps.newHashMap();
68 |
69 |
70 | public static GoodsInfo of(Long goodsId, Long skuId, List categoryIds, int num, long salePrice, String name, Map goodsExtra) {
71 | GoodsInfo goodsInfo = new GoodsInfo();
72 | goodsInfo.setGoodsId(goodsId);
73 | goodsInfo.setCategoryIds(categoryIds);
74 | goodsInfo.setNum(num);
75 | goodsInfo.setSkuId(skuId);
76 | goodsInfo.setSalePrice(salePrice);
77 | goodsInfo.setName(name);
78 | goodsInfo.setGoodsExtra(goodsExtra);
79 | return goodsInfo;
80 | }
81 |
82 | @Override
83 | public GoodsInfo clone() throws CloneNotSupportedException {
84 | return (GoodsInfo) super.clone();
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/model/goods/GoodsItem.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.model.goods;
18 |
19 | import com.gch.discount.core.utils.IdGenerator;
20 | import com.google.common.collect.Lists;
21 | import com.google.common.collect.Maps;
22 | import lombok.*;
23 |
24 | import java.io.Serializable;
25 | import java.util.List;
26 | import java.util.Map;
27 | import java.util.Objects;
28 | import java.util.function.Consumer;
29 |
30 | /**
31 | * 拆分后的商品,比如一个商品GoodsInfo买了2件则会产出2个GoodsItem
32 | * @author: GaoSSR
33 | * @date: 2023/7
34 | */
35 | @Data
36 | public class GoodsItem extends GoodsInfo implements Serializable, Comparable, Cloneable {
37 |
38 | /**
39 | * 根据基本信息构造具体的计算商品,复制属性,以及单商品唯一id
40 | * @param calculateId
41 | * @param goodsInfo
42 | */
43 | public GoodsItem(long calculateId, GoodsInfo goodsInfo) {
44 | this.calculateId = calculateId;
45 | this.setGoodsId(goodsInfo.getGoodsId());
46 | this.setCategoryIds(goodsInfo.getCategoryIds());
47 | this.setName(goodsInfo.getName());
48 | this.setSkuId(goodsInfo.getSkuId());
49 | this.setSalePrice(goodsInfo.getSalePrice());
50 | }
51 |
52 | /**
53 | * 引擎计算时使用的id,每个单独商品一个
54 | */
55 | private Long calculateId;
56 |
57 | /**
58 | * 商品扩展属性
59 | */
60 | private Map extra = Maps.newHashMap();
61 |
62 | /**
63 | * 根据商品信息(数量),生成计算时候需要的具体商品(单个)
64 | *
65 | * @param goodsInfo 商品信息
66 | * @param idGenerator id生成器
67 | * @param consumer 在创建商品的同时对extra中的内容进行初始化
68 | */
69 | @SuppressWarnings("unchecked")
70 | public static List generateItems(GoodsInfo goodsInfo, IdGenerator idGenerator, Consumer consumer) {
71 | if (Objects.isNull(goodsInfo)) {
72 | return Lists.newArrayList();
73 | }
74 | List goodsItems = Lists.newArrayList();
75 | for (int i = 0; i < goodsInfo.getNum(); i++) {
76 | T item = (T) new GoodsItem(idGenerator.nextId(), goodsInfo);
77 | consumer.accept(item);
78 | goodsItems.add(item);
79 | }
80 | return goodsItems;
81 | }
82 |
83 | @Override
84 | public boolean equals(Object o) {
85 | if (this == o) {
86 | return true;
87 | }
88 | if (o == null || getClass() != o.getClass()) {
89 | return false;
90 | }
91 | GoodsItem goodsItem = (GoodsItem) o;
92 | return Objects.equals(calculateId, goodsItem.calculateId);
93 | }
94 |
95 | @Override
96 | public int hashCode() {
97 | return Objects.hash(calculateId);
98 | }
99 |
100 | @Override
101 | public int compareTo(GoodsItem o) {
102 | return this.getCalculateId().compareTo(o.getCalculateId());
103 | }
104 |
105 | @Override
106 | public GoodsItem clone() throws CloneNotSupportedException {
107 | return (GoodsItem) super.clone();
108 | }
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/permutation/Permutation.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.permutation;
18 |
19 | import com.gch.discount.core.aware.CalculatorRouter;
20 | import com.gch.discount.core.discount.Calculator;
21 | import com.gch.discount.core.model.common.*;
22 | import com.gch.discount.core.model.goods.GoodsItem;
23 | import com.google.common.collect.Collections2;
24 | import com.google.common.collect.Maps;
25 | import com.google.common.collect.Sets;
26 | import org.apache.commons.collections4.CollectionUtils;
27 |
28 | import java.util.*;
29 | import java.util.stream.Collectors;
30 | import java.util.stream.IntStream;
31 |
32 |
33 | /**
34 | * 全排列计算引擎
35 | * @author: GaoSSR
36 | * @date: 2023/8
37 | */
38 |
39 | @SuppressWarnings("all")
40 | public abstract class Permutation {
41 |
42 | /**
43 | * 根据注解路由到目标Calculator
44 | */
45 | private CalculatorRouter calculatorRouter;
46 |
47 | /**
48 | * 上下文
49 | */
50 | private DiscountContext context;
51 |
52 | /**
53 | * 必须使用的优惠,比如用户手动选择的优惠
54 | */
55 | private final Set mustUseSet = Sets.newHashSet();
56 |
57 | /**
58 | * 缓存,key是calcKey生成的数字,value是保存点
59 | */
60 | private final Map> cache = Maps.newHashMap();
61 |
62 | /**
63 | * 将calculatorRouter绑定到当前Permutation
64 | * @param calculatorRouter 路由器
65 | * @return
66 | */
67 | public Permutation build(CalculatorRouter calculatorRouter) {
68 | this.calculatorRouter = calculatorRouter;
69 | return this;
70 | }
71 |
72 | /**
73 | * 1-SUPPORTEDSIZE 之间所有排列组合的记录
74 | */
75 | private final static Map>> PERMUTATIONS = Maps.newHashMap();
76 |
77 | /**
78 | * 最大支持的共享组长度
79 | */
80 | public final static int SUPPORTEDSIZE = 7;
81 |
82 | static {
83 | //前置计算 1-SUPPORTEDSIZE 之间所有排列组合
84 | for (byte i = 1; i <= SUPPORTEDSIZE; i++) {
85 | PERMUTATIONS.put((int) i, Collections2.permutations(IntStream.range(0, i).boxed()
86 | .map(x -> (byte) x.intValue()).collect(Collectors.toList())));
87 | }
88 | }
89 |
90 | /**
91 | * 计算用户选择的优惠组合是否有可行解
92 | * @param context 上下文
93 | * @return
94 | */
95 | public boolean findSolution(DiscountContext context) {
96 | int size = context.getDiscountWrappers().size();
97 | this.context = context;
98 | if (size == 0) {
99 | return false;
100 | }
101 | Collection
> list = PERMUTATIONS.get(size);
102 | for (List a : list) {
103 | if (findSolution(context, a)) {
104 | return true;
105 | }
106 | }
107 | cache.clear();
108 | mustUseSet.clear();
109 | return false;
110 | }
111 |
112 | /**
113 | * 计算最优解
114 | * @param context 上下文
115 | * @return
116 | */
117 | public void perm(DiscountContext context) {
118 | int size = context.getDiscountWrappers().size();
119 | this.context = context;
120 | loadMustUseDiscount();
121 | if (size == 0) {
122 | return;
123 | }
124 | Collection> list = PERMUTATIONS.get(size);
125 | for (List a : list) {
126 | boolean isBetter = executeCalc(this.context, a);
127 | if (isBetter) {
128 | //若出现比当前结果更优的结果则替换
129 | updateRecord(this.context.getCalcResult());
130 | }
131 | }
132 | cache.clear();
133 | mustUseSet.clear();
134 | }
135 |
136 | private void loadMustUseDiscount() {
137 | for (int i = 0; i < context.getDiscountWrappers().size(); i++) {
138 | if (context.getDiscountWrappers().get(i).isMustUse()) {
139 | this.mustUseSet.add((byte) i);
140 | }
141 | }
142 | }
143 |
144 | /**
145 | * 根据byte数组生成唯一数字作为Map的key,避免字符串拼接等低效操作
146 | */
147 | private static Integer calcKey(List a) {
148 | return a.size() >= 3 ? (a.get(0) << 6) + (a.get(1) << 3) + a.get(2) : 0;
149 | }
150 |
151 | /**
152 | * 若出现比当前结果更优的结果则替换
153 | * @param result 当前的计算结果
154 | */
155 | private void updateRecord(CalcResult result) {
156 | result.setFinalPrice(result.getCurFinalPrice());
157 | System.arraycopy(result.getCurStages(), 0, result.getStages(), 0, result.getStages().length);
158 | }
159 |
160 | /**
161 | * 找到可行解,这种情况list中所有优惠必须被使用
162 | * @param context 上下文
163 | * @param a 当前计算的排列
164 | */
165 | private boolean findSolution(DiscountContext context, List a) {
166 | Integer k = calcKey(a);
167 | boolean canOptimize = enableOptimize(a) && cache.containsKey(k);
168 | initInner(canOptimize, k);
169 | for (int i = canOptimize ? 3 : 0; i < a.size(); i++) {
170 | DiscountWrapper wrapper = context.getDiscountWrappers().get(a.get(i));
171 | Calculator calculator = (Calculator) calculatorRouter.getService(wrapper.getType());
172 | //路由目标的计算器实现
173 | if (canOptimize && checkIfWakeUpJump(context.getDiscountWrappers().get(a.get(2)), wrapper)) {
174 | //还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出
175 | break;
176 | }
177 | if (Objects.nonNull(calculator)) {
178 | //执行计算器
179 | if (!calcInner(calculator, wrapper, a, i)) {
180 | return false;
181 | }
182 | CalcStage cs = context.getCalcResult().getCurStages()[i];
183 | if (Objects.isNull(cs)) {
184 | //执行当前排列,若存在未使用的优惠则证明当前排列不可行
185 | return false;
186 | }
187 | //优惠长度为5、6、7 将开启优化,只缓存走到第3个节点的部分
188 | cacheSnapshot(a, i, k);
189 | }
190 | }
191 | return true;
192 | }
193 |
194 | private void cacheSnapshot(List a, int i, Integer k) {
195 | if (enableOptimize(a) && i == 2 && !cache.containsKey(k)) {
196 | cache.put(k, makeSnapshot(context.getGoodsItems()));
197 | }
198 | }
199 |
200 | private void initInner(boolean canOptimize, Integer k) {
201 | if (canOptimize) {
202 | //若可优化则还原之前的保存点
203 | backToSnapshot(k);
204 | } else {
205 | //若不可优化则老老实实初始化
206 | initCtx();
207 | }
208 | }
209 |
210 | private boolean calcInner(Calculator calculator, DiscountWrapper wrapper, List a, int i) {
211 | long price = calculator.calcWarp(context, wrapper, context.getRecords(), a.get(i), i);
212 | if (price < 0) {
213 | return false;
214 | }
215 | if (i < a.size() - 1) {
216 | int order = wrapper.getDiscountConfig().getCalculateGroup();
217 | int nextOrder = context.getDiscountWrappers().get(a.get(i + 1)).getDiscountConfig().getCalculateGroup();
218 | if (order > nextOrder) {
219 | //优先级不符合则跳出
220 | return false;
221 | }
222 | }
223 | return true;
224 | }
225 |
226 | /**
227 | * 根据数组顺序执行计算器
228 | */
229 | public boolean executeCalc(DiscountContext context, List a) {
230 | Integer k = calcKey(a);
231 | boolean canOptimize = enableOptimize(a) && cache.containsKey(k);
232 | initInner(canOptimize, k);
233 | for (int i = canOptimize ? 3 : 0; i < a.size(); i++) {
234 | DiscountWrapper wrapper = context.getDiscountWrappers().get(a.get(i));
235 | Calculator calculator = (Calculator) calculatorRouter.getService(wrapper.getType());
236 | //路由目标的计算器实现
237 | if (canOptimize && checkIfWakeUpJump(context.getDiscountWrappers().get(a.get(2)), wrapper)) {
238 | //还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出
239 | break;
240 | }
241 | if (Objects.nonNull(calculator)) {
242 | //执行计算器
243 | if (!calcInner(calculator, wrapper, a, i)) {
244 | return false;
245 | }
246 | //优惠长度为5、6、7 将开启优化,只缓存走到第3个节点的部分
247 | cacheSnapshot(a, i, k);
248 | }
249 | }
250 | long curPrice = context.getCalcResult().getCurPrice();
251 | context.getCalcResult().setCurFinalPrice(curPrice);
252 | CalcStage[] stages = context.getCalcResult().getCurStages();
253 | return curPrice < context.getCalcResult().getFinalPrice() && (CollectionUtils.isEmpty(this.mustUseSet) || isMustUse(stages, this.mustUseSet)) ||
254 | //相同最优解处理逻辑
255 | curPrice == context.getCalcResult().getFinalPrice() && (CollectionUtils.isEmpty(this.mustUseSet) || isMustUse(stages, this.mustUseSet)) && sameOptimumCondition(stages);
256 | }
257 |
258 | /**
259 | * 还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出
260 | * @param cachedWrap 保存点的最后一个优惠节点
261 | * @param wrapper 当前优惠节点
262 | */
263 | private boolean checkIfWakeUpJump(DiscountWrapper cachedWrap, DiscountWrapper wrapper) {
264 | return cachedWrap.getDiscountConfig().getCalculateGroup() > wrapper.getDiscountConfig().getCalculateGroup();
265 | }
266 |
267 |
268 | /**
269 | * 全排列计算后判断位置是否匹配
270 | * @param stages 当前stage数组
271 | * @param pos 必须使用的优惠索引
272 | * @return
273 | */
274 | private boolean isMustUse(CalcStage[] stages, Set pos) {
275 | int c = 0;
276 | for (CalcStage stage : stages) {
277 | if (Objects.isNull(stage)) {
278 | continue;
279 | }
280 | if (pos.contains(stage.getIndex())) {
281 | c++;
282 | }
283 | }
284 | return c == pos.size();
285 | }
286 |
287 |
288 | /**
289 | * 初始化上下文,清理上一排列留下的脏数据
290 | */
291 | private void initCtx() {
292 | context.getCalcResult().setCurPrice(context.getOriginalPrice());
293 | CalcStage[] curArr = context.getCalcResult().getCurStages();
294 | //每次排列计算前初始化curStages为null
295 | Arrays.fill(curArr, null);
296 | //每次排列计算前reset usedList 中的单品价格,并清空
297 | context.getGoodsItems().forEach(this::resetItems);
298 | //清空黑名单
299 | context.getRecords().clear();
300 | //初始化Context
301 | resetContext(context);
302 | }
303 |
304 | /**
305 | * 构建保存点
306 | * @param goods 商品列表
307 | */
308 | private CalcState makeSnapshot(List goods) {
309 | CalcState state = new CalcState<>();
310 | state.setCurPrice(context.getCalcResult().getCurPrice());
311 | state.setCurStages(copyStage(context.getCalcResult().getCurStages()));
312 | state.setRecords(copyRecord(context.getRecords()));
313 | makeSnapshot(state, context);
314 | return state;
315 | }
316 |
317 |
318 | /**
319 | * 返回保存点
320 | * @param k 缓存的key
321 | */
322 | private void backToSnapshot(Integer k) {
323 | CalcState state = (CalcState) cache.get(k);
324 | context.getCalcResult().setCurPrice(state.getCurPrice());
325 | context.getCalcResult().setCurStages(copyStage(state.getCurStages()));
326 | context.setRecords(copyRecord(state.getRecords()));
327 | backToSnapshot(state, context);
328 | }
329 |
330 |
331 | /**
332 | * 复制stages
333 | * @param curStages 当前stages
334 | */
335 | private CalcStage[] copyStage(CalcStage[] curStages) {
336 | CalcStage[] cs = new CalcStage[curStages.length];
337 | System.arraycopy(curStages, 0, cs, 0, curStages.length);
338 | return cs;
339 | }
340 |
341 | /**
342 | * clone商品当前状态,转成map便于查找
343 | * @param goods 商品列表
344 | * @return
345 | */
346 | protected Map copyGoods(List goods) {
347 | Map map = Maps.newHashMap();
348 | for (T good : goods) {
349 | try {
350 | map.put(good.getCalculateId(), (T) good.clone());
351 | } catch (Exception ignore) {
352 | }
353 | }
354 | return map;
355 | }
356 |
357 | /**
358 | * 复制享受过优惠的商品记录,只用到calculateId,因此不对对象进行clone
359 | * @param records 享受过优惠的商品记录
360 | */
361 | private Map copyRecord(Map records) {
362 | return Maps.newHashMap(records);
363 | }
364 |
365 | /**
366 | * 相同最优解的处理逻辑,交给业务来实现
367 | *
368 | * @param stages 最终的stage数组
369 | * @param curStages 当前的stage数组
370 | * @return
371 | */
372 | protected abstract boolean sameOptimumCondition(CalcStage[] curStages);
373 |
374 | /**
375 | * context参数的重置逻辑,交给业务来实现
376 | * @param context 上下文
377 | */
378 | protected abstract void resetContext(DiscountContext context);
379 |
380 | /**
381 | * 开启缓存的条件,如 a.size>4
382 | * @param a 优惠排列
383 | */
384 | protected abstract boolean enableOptimize(List a);
385 |
386 | /**
387 | * 商品参数的重置逻辑,交给业务来实现
388 | * @param item 单品
389 | */
390 | protected abstract void resetItems(T item);
391 |
392 | /**
393 | * 业务将状态记录到保存点
394 | * @param state 保存点对象
395 | */
396 | protected abstract void makeSnapshot(CalcState state, DiscountContext context);
397 |
398 | /**
399 | * 业务返回保存点状态
400 | * @param state 保存点对象
401 | */
402 | protected abstract void backToSnapshot(CalcState state, DiscountContext context);
403 | }
404 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/precompute/PreCompute.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.precompute;
18 |
19 | import com.gch.discount.core.model.common.DiscountWrapper;
20 | import com.gch.discount.core.model.goods.GoodsItem;
21 |
22 | import java.util.List;
23 | import java.util.Map;
24 | import java.util.Set;
25 |
26 | /**
27 | * 预计算,把一些耗时操作放在Context中操作
28 | * @author: GaoSSR
29 | * @date: 2023/8
30 | */
31 | public interface PreCompute {
32 |
33 | /**
34 | * 判断符合条件的活动类型,符合才会执行preComputeItems
35 | */
36 | Set matchTypes();
37 |
38 | /**
39 | * 对商品做一些复杂集合操作
40 | * @param items 当前参与优惠的商品
41 | * @param discount 当前优惠
42 | * @param preCompute 存储计算的结果
43 | */
44 | void preComputeItems(List items, DiscountWrapper discount, Map preCompute);
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/precompute/PreComputeHolder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.precompute;
18 |
19 | import com.google.common.collect.Sets;
20 | import org.apache.commons.lang3.StringUtils;
21 | import org.reflections.Reflections;
22 | import org.springframework.core.io.FileSystemResource;
23 | import org.springframework.core.io.support.PropertiesLoaderUtils;
24 |
25 | import java.util.Objects;
26 | import java.util.Properties;
27 | import java.util.Set;
28 |
29 | /**
30 | * PreCompute实现类的加载器,会扫描calculator-core文件中的precompute.path属性
31 | * @author: GaoSSR
32 | * @date: 2023/8
33 | */
34 | @SuppressWarnings("all")
35 | public class PreComputeHolder {
36 | public static Set COMPUTES = Sets.newHashSet();
37 | private final static String PATH = "precompute.path";
38 |
39 | static {
40 | Properties properties = new Properties();
41 | try {
42 | properties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(Objects.requireNonNull(PreComputeHolder.class.getClassLoader().getResource("calculator-core.properties")).getPath()));
43 | } catch (Exception ignore) {
44 | }
45 | String path = properties.getProperty(PATH);
46 | if (StringUtils.isNotBlank(path)) {
47 | Reflections reflections = new Reflections(path);
48 | Set> subTypes = reflections.getSubTypesOf(PreCompute.class);
49 | for (Class extends PreCompute> clazz : subTypes) {
50 | try {
51 | COMPUTES.add(clazz.newInstance());
52 | } catch (Exception ignore) {
53 | }
54 | }
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/utils/DiscountGroupUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.utils;
18 |
19 | import com.gch.discount.core.model.common.DiscountGroup;
20 | import com.gch.discount.core.model.common.DiscountWrapper;
21 | import com.gch.discount.core.model.common.Item;
22 | import com.gch.discount.core.permutation.Permutation;
23 | import com.google.common.collect.Lists;
24 | import com.google.common.collect.Maps;
25 | import com.google.common.collect.Sets;
26 | import com.google.common.util.concurrent.AtomicLongMap;
27 | import org.apache.commons.collections4.CollectionUtils;
28 | import org.apache.commons.collections4.MapUtils;
29 | import org.apache.commons.lang3.tuple.Pair;
30 | import java.util.*;
31 | import java.util.stream.Collectors;
32 |
33 | /**
34 | * ID生成器,用于生成每次计算的商品id
35 | * 非线程安全,不可以在多线程共享。 每次计算创建一个,用于生成具体每一个商品的唯一ID
36 | * @author: GaoSSR
37 | * @date: 2023/7
38 | */
39 | public class DiscountGroupUtil {
40 |
41 | private static final String EXCLUDE="exclude";
42 |
43 | /**
44 | * 返回所有共享组
45 | * Pair的left是长度不超过 Permutation.SUPPORTEDSIZE 的内容,right是第 Permutation.SUPPORTEDSIZE+1
46 | * 种优惠即其他优惠(若有),即不参与全排列的优惠
47 | * @param groups
48 | * @param inMap
49 | * @return
50 | */
51 | public static List,Set>> transform(List> groups, Map> inMap) {
52 | List,Set>> resultList = Lists.newArrayList();
53 | List> list = mergeGroups(groups,inMap);
54 | if(CollectionUtils.isEmpty(list)){
55 | return Lists.newArrayList();
56 | }
57 | for(List- items:list){
58 | Set discountWrappers = items.stream().map(x->{
59 | if(inMap.containsKey(x.getType())){
60 | Map m=inMap.get(x.getType());
61 | if(m.containsKey(x.getId())){
62 | return m.get(x.getId());
63 | }
64 | }
65 | return null;
66 | }).filter(Objects::nonNull).collect(Collectors.toSet());
67 | if(CollectionUtils.isNotEmpty(discountWrappers) && discountWrappers.size()>=2){
68 | if(discountWrappers.size()> Permutation.SUPPORTEDSIZE) {
69 | resultList.add(balanceLR(discountWrappers));
70 | }else{
71 | resultList.add(Pair.of(discountWrappers, Sets.newHashSet()));
72 | }
73 | }
74 | }
75 | //优先计算短的共享组
76 | return resultList.stream().sorted(Comparator.comparing(x->x.getLeft().size(),Collections.reverseOrder())).collect(Collectors.toList());
77 | }
78 |
79 | /**
80 | * 保证mustuse的优惠进入left集合
81 | * @param discountWrappers 当前可用优惠
82 | */
83 | private static Pair,Set> balanceLR(Set discountWrappers){
84 | Set left=Sets.newHashSet();
85 | Set right=Sets.newHashSet();
86 | for(DiscountWrapper wrapper:discountWrappers){
87 | if(wrapper.isMustUse()){
88 | left.add(wrapper);
89 | }else{
90 | right.add(wrapper);
91 | }
92 | }
93 | if(left.size() it = right.iterator();
96 | while (c>0&&it.hasNext()){
97 | DiscountWrapper w = it.next();
98 | left.add(w);
99 | it.remove();
100 | c--;
101 | }
102 | }else if(left.size()>Permutation.SUPPORTEDSIZE){
103 | int c = left.size()-Permutation.SUPPORTEDSIZE;
104 | Iterator it = left.iterator();
105 | while (c>0&&it.hasNext()){
106 | DiscountWrapper w = it.next();
107 | right.add(w);
108 | it.remove();
109 | c--;
110 | }
111 | }
112 | return Pair.of(left,right);
113 | }
114 |
115 | /**
116 | * 合并规则转化为共享组
117 | * @param groups 所有规则大组
118 | * @param inMap 实际可用优惠
119 | */
120 | private static List
> mergeGroups(List> groups,Map> inMap){
121 | if(CollectionUtils.isEmpty(groups) || MapUtils.isEmpty(inMap)){
122 | return null;
123 | }
124 | //resultList 接收最终的结果
125 | List> resultList = Lists.newArrayList();
126 | //ctx 全局计数器,对于独立共享组多次被使用进行删除(唯一需要去重的场景)
127 | AtomicLongMap ctx = AtomicLongMap.create();
128 | //索引,存放可能需要删除的key
129 | Map idxMap = Maps.newHashMap();
130 | for(List list:groups){
131 | mergeGroup(list,inMap,ctx,idxMap,resultList);
132 | }
133 | Map map = ctx.asMap();
134 | List orderedList = Lists.newArrayList();
135 | for(Map.Entry e:map.entrySet()){
136 | Integer idx = idxMap.get(e.getKey());
137 | if(Objects.nonNull(idx)&&e.getValue()>1){
138 | orderedList.add(idxMap.get(e.getKey()));
139 | }
140 | }
141 | orderedList.sort(Collections.reverseOrder());
142 | //从后往前删除,否则索引会出问题
143 | for(Integer i:orderedList){
144 | resultList.remove(i.intValue());
145 | }
146 | return resultList.stream().filter(CollectionUtils::isNotEmpty).collect(Collectors.toList());
147 | }
148 |
149 | private static void mergeGroup(List groups,Map> inMap,
150 | AtomicLongMap ctx,Map idxMap,
151 | List> resultList){
152 | if(CollectionUtils.isEmpty(groups)){
153 | return ;
154 | }
155 | List- xList = groups.get(0).filterItems(inMap);
156 | if(CollectionUtils.isEmpty(xList)){
157 | return ;
158 | }
159 | if(groups.size()==1){
160 | //必然是共享组
161 | //存入全局上下文,去重时使用,这里累计次数,若次数大于1,需要在最外层移除此共享组
162 | String key = uniqueKey(xList);
163 | ctx.incrementAndGet(key);
164 | //记录索引,以便删除
165 | idxMap.put(key,resultList.size());
166 | resultList.add(xList);
167 | }else{
168 | //yList必然是互斥的
169 | List
- yList = groups.get(1).filterItems(inMap);
170 | if(Objects.equals(EXCLUDE,groups.get(0).getRelation())){
171 | //产品设计规避了重复的情况,无需去重
172 | for(Item item:xList){
173 | for(Item item1:yList){
174 | resultList.add(Lists.newArrayList(item,item1));
175 | }
176 | }
177 | }else{
178 | //存入全局上下文,去重时使用,这里累计次数,若次数大于1,需要在最外层移除此共享组
179 | String k = uniqueKey(xList);
180 | for(Item item:yList){
181 | ctx.incrementAndGet(k);
182 | List
- xCopy = Lists.newArrayList(xList);
183 | xCopy.add(item);
184 | resultList.add(xCopy);
185 | }
186 | }
187 | }
188 | }
189 |
190 | private static String uniqueKey(List
- list){
191 | return list.stream().map(i->i.getType()+i.getId()).sorted().collect(Collectors.joining());
192 | }
193 |
194 | }
195 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/utils/IdGenerator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.utils;
18 |
19 | /**
20 | * ID生成器,用于生成每次计算的商品id
21 | * 非线程安全,不可在多线程共享。 每次计算创建一个,用于生成具体每一个商品的唯一ID
22 | * @author: GaoSSR
23 | * @date: 2023/7
24 | */
25 | public class IdGenerator {
26 |
27 | /**
28 | * 新建一个对象,默认构造
29 | */
30 | public static IdGenerator getInstance() {
31 | return new IdGenerator();
32 | }
33 |
34 | /**
35 | * 当前ID,默认从1开始
36 | */
37 | private long currentId = 1;
38 |
39 | /**
40 | * 按序列生成一个ID
41 | */
42 | public long nextId() {
43 | return currentId++;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/core/utils/LimitingUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2023 GaoSSR
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.gch.discount.core.utils;
18 |
19 | /**
20 | * 统计计算次数的工具,在机器负载较大时,作为放弃后面计算的条件
21 | * @author: GaoSSR
22 | * @date: 2023/8
23 | */
24 | public class LimitingUtil {
25 |
26 | /**
27 | * 统计计算次数
28 | * 根据性能压测结果,对于多个共享组来说是必要的
29 | * @param length 共享组的长度
30 | */
31 | public static int count(int length){
32 | switch (length){
33 | case 1:return 1;
34 | //下面的计算公式是 x!*x
35 | case 2:return 4;
36 | case 3:return 18;
37 | //下面的计算公式是 x!*(x-3)+p(x,3)
38 | case 4:return 48;
39 | case 5:return 300;
40 | case 6:return 2280;
41 | case 7:return 20370;
42 | default:return 0;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/demo/App.java:
--------------------------------------------------------------------------------
1 | package com.gch.discount.demo;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 | import org.springframework.context.annotation.ComponentScan;
6 |
7 | @SpringBootApplication
8 | @ComponentScan("com.gch.discount")
9 | public class App {
10 | public static void main(String[] args) {
11 | SpringApplication.run(App.class, args);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/demo/biz/Flowable.java:
--------------------------------------------------------------------------------
1 | package com.gch.discount.demo.biz;
2 |
3 | import com.gch.discount.core.model.common.CalcStage;
4 | import com.gch.discount.core.model.common.CalcState;
5 | import com.gch.discount.core.model.common.DiscountContext;
6 | import com.gch.discount.core.model.goods.GoodsItem;
7 | import com.gch.discount.core.permutation.Permutation;
8 | import com.gch.discount.demo.biz.constant.Constant;
9 |
10 | import java.util.List;
11 |
12 | public class Flowable extends Permutation {
13 | @Override
14 | protected boolean enableOptimize(List a) {
15 | return false;
16 | }
17 |
18 | @Override
19 | protected boolean sameOptimumCondition(CalcStage[] curStages) {
20 | return false;
21 | }
22 |
23 | @Override
24 | protected void resetContext(DiscountContext context) {
25 |
26 | }
27 |
28 | @Override
29 | protected void resetItems(GoodsItem item) {
30 | item.getExtra().put(Constant.UPDATEABLEPRICE, item.getSalePrice());
31 | }
32 |
33 | @Override
34 | protected void makeSnapshot(CalcState state, DiscountContext context) {
35 |
36 | }
37 |
38 | @Override
39 | protected void backToSnapshot(CalcState state, DiscountContext context) {
40 |
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/demo/biz/TestController.java:
--------------------------------------------------------------------------------
1 | package com.gch.discount.demo.biz;
2 |
3 | import com.gch.discount.core.enums.GroupRelation;
4 | import com.gch.discount.core.model.common.*;
5 | import com.gch.discount.core.model.goods.GoodsInfo;
6 | import com.gch.discount.core.model.goods.GoodsItem;
7 | import com.gch.discount.core.utils.DiscountGroupUtil;
8 | import com.gch.discount.core.utils.IdGenerator;
9 | import com.gch.discount.core.utils.LimitingUtil;
10 | import com.gch.discount.demo.biz.constant.Constant;
11 | import com.google.common.collect.ImmutableMap;
12 | import com.google.common.collect.Lists;
13 | import org.apache.commons.lang3.tuple.Pair;
14 | import org.springframework.stereotype.Controller;
15 | import org.springframework.web.bind.annotation.RequestMapping;
16 | import org.springframework.web.bind.annotation.ResponseBody;
17 | import com.gch.discount.core.aware.CalculatorRouter;
18 |
19 | import java.util.*;
20 | import java.util.stream.Collectors;
21 |
22 | @Controller
23 | public class TestController {
24 | private final CalculatorRouter calculatorRouter;
25 |
26 | public TestController(CalculatorRouter calculatorRouter) {
27 | this.calculatorRouter = calculatorRouter;
28 | }
29 |
30 | @RequestMapping("test")
31 | @ResponseBody
32 | public Object test() {
33 | //mock商品
34 | List items = mockItems();
35 | //mock组关系并转化为共享组
36 | List, Set>> pairs = transform(mockGroups());
37 | //全局最优计算过程
38 | List globalStages = Lists.newArrayList();
39 | int count = 0;
40 | //订单总金额
41 | long totalPrice = items.stream().mapToLong(GoodsInfo::getSalePrice).sum();
42 | long globalPrice = totalPrice;
43 | //构建计算流
44 | Flowable flowable = (Flowable) new Flowable().build(calculatorRouter);
45 | for (Pair, Set> set : pairs) {
46 | //统计算力
47 | count += LimitingUtil.count(set.getLeft().size());
48 | if (count > 100000) {
49 | break;
50 | }
51 | List wrappers = Lists.newArrayList(set.getLeft());
52 | DiscountContext ctx = DiscountContext.create(totalPrice, Lists.newArrayList(items), wrappers);
53 | flowable.perm(ctx);
54 | if (ctx.getCalcResult().getFinalPrice() < globalPrice) {
55 | globalStages = Arrays.asList(ctx.getCalcResult().getStages());
56 | globalPrice = ctx.getCalcResult().getFinalPrice();
57 | }
58 | }
59 | return Pair.of(globalPrice, globalStages);
60 | }
61 |
62 | private List
> mockGroups() {
63 | List> groups = Lists.newArrayList();
64 | DiscountGroup group = new DiscountGroup();
65 | group.setRelation(GroupRelation.SHARE.getType());
66 | group.setItems(Lists.newArrayList(new Item("zhekou", "1"), new Item("manjian", "2"), new Item("manzeng", "3")));
67 | groups.add(Lists.newArrayList(group));
68 | return groups;
69 | }
70 |
71 | private List mockItems() {
72 | IdGenerator idGenerator = IdGenerator.getInstance();
73 | GoodsInfo goodsInfo = GoodsInfo.of(1001L, 2001L, null, 4, 20 * 100, "产品1", null);
74 | GoodsInfo goodsInfo2 = GoodsInfo.of(1001L, 2002L, null, 2, 10 * 100, "产品1", null);
75 | List items = GoodsItem.generateItems(goodsInfo, idGenerator, x -> x.getExtra().put(Constant.UPDATEABLEPRICE, x.getSalePrice()));
76 | items.addAll(GoodsItem.generateItems(goodsInfo2, idGenerator, x -> x.getExtra().put(Constant.UPDATEABLEPRICE, x.getSalePrice())));
77 | return items;
78 | }
79 |
80 | private List, Set>> transform(List> groups) {
81 | List wrapperList = Lists.newArrayList(
82 | DiscountWrapper.of("zhekou", "1", "折扣", false, new DiscountConfig()),
83 | DiscountWrapper.of("manjian", "2", "满减", false, new DiscountConfig())
84 | );
85 | Map> inMap = wrapperList.stream().collect(Collectors.toMap(DiscountWrapper::getType, x -> ImmutableMap.of(x.getId(), x)));
86 | return DiscountGroupUtil.transform(groups, inMap);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/demo/biz/calc/ManjianCalc.java:
--------------------------------------------------------------------------------
1 | package com.gch.discount.demo.biz.calc;
2 |
3 | import com.gch.discount.core.discount.impl.AbstractCalculator;
4 | import com.gch.discount.core.model.common.CalcStage;
5 | import com.gch.discount.core.model.common.DiscountContext;
6 | import com.gch.discount.core.model.common.DiscountWrapper;
7 | import com.gch.discount.core.model.goods.GoodsItem;
8 | import com.gch.discount.demo.biz.constant.Constant;
9 | import com.google.common.collect.Lists;
10 | import org.springframework.stereotype.Component;
11 |
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | @Component("manjian")
16 | public class ManjianCalc extends AbstractCalculator {
17 | @Override
18 | public long calc(DiscountContext context, DiscountWrapper discountWrapper, Map records, long prevStagePrice, CalcStage curStage) {
19 | List items = Lists.newArrayList(context.getDiscountItemGroup().get(discountWrapper.getId()));
20 | if (prevStagePrice >= 100 * 100) {
21 | prevStagePrice = prevStagePrice - 20 * 100;
22 | }
23 | //均摊
24 | for (GoodsItem item : items) {
25 | item.getExtra().put(Constant.UPDATEABLEPRICE, (long) item.getExtra().get(Constant.UPDATEABLEPRICE) - (long) (20 * 100 / items.size()));
26 | }
27 | return prevStagePrice;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/demo/biz/calc/ZhekouCalc.java:
--------------------------------------------------------------------------------
1 | package com.gch.discount.demo.biz.calc;
2 |
3 | import com.gch.discount.core.discount.impl.AbstractCalculator;
4 | import com.gch.discount.core.model.common.CalcStage;
5 | import com.gch.discount.core.model.common.DiscountContext;
6 | import com.gch.discount.core.model.common.DiscountWrapper;
7 | import com.gch.discount.core.model.goods.GoodsItem;
8 | import com.gch.discount.demo.biz.constant.Constant;
9 | import com.google.common.collect.Lists;
10 | import org.apache.commons.collections4.CollectionUtils;
11 | import org.springframework.stereotype.Component;
12 |
13 | import java.util.Collection;
14 | import java.util.List;
15 | import java.util.Map;
16 |
17 | @Component("zhekou")
18 | @SuppressWarnings("unchecked")
19 | public class ZhekouCalc extends AbstractCalculator {
20 | @Override
21 | public long calc(DiscountContext context, DiscountWrapper discountWrapper, Map records, long prevStagePrice, CalcStage curStage) {
22 | List items = Lists.newArrayList(context.getDiscountItemGroup().get(discountWrapper.getId()));
23 | Map> map = (Map>) context.getPreCompute().get("GroupBySkuIdPreCompute");
24 | long maxPrice = 0L;
25 | Collection group = CollectionUtils.EMPTY_COLLECTION;
26 | for (Collection c : map.values()) {
27 | long tmp = (long) c.iterator().next().getExtra().get(Constant.UPDATEABLEPRICE);
28 | if (tmp > maxPrice) {
29 | maxPrice = tmp;
30 | group = c;
31 | }
32 | }
33 | long discount = (long) (maxPrice * group.size() * 0.2);
34 | //均摊
35 | for (GoodsItem item : group) {
36 | item.getExtra().put(Constant.UPDATEABLEPRICE, (long) item.getExtra().get(Constant.UPDATEABLEPRICE) - discount / items.size());
37 | }
38 | return prevStagePrice - discount;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/demo/biz/constant/Constant.java:
--------------------------------------------------------------------------------
1 | package com.gch.discount.demo.biz.constant;
2 |
3 | public class Constant {
4 |
5 | public static final String UPDATEABLEPRICE = "updateablePrice";
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/gch/discount/demo/biz/precompute/PreGroupBy.java:
--------------------------------------------------------------------------------
1 | package com.gch.discount.demo.biz.precompute;
2 |
3 | import com.gch.discount.core.model.common.DiscountWrapper;
4 | import com.gch.discount.core.model.goods.GoodsInfo;
5 | import com.gch.discount.core.model.goods.GoodsItem;
6 | import com.gch.discount.core.precompute.PreCompute;
7 | import com.google.common.collect.Sets;
8 |
9 | import java.util.List;
10 | import java.util.Map;
11 | import java.util.Set;
12 | import java.util.stream.Collectors;
13 |
14 | public class PreGroupBy implements PreCompute {
15 | @Override
16 | public Set matchTypes() {
17 | return Sets.newHashSet("zhekou");
18 | }
19 |
20 | @Override
21 | public void preComputeItems(List items, DiscountWrapper discount, Map preCompute) {
22 | preCompute.put("GroupBySkuIdPreCompute", items.stream().collect(Collectors.groupingBy
23 | (GoodsInfo::getSkuId, Collectors.collectingAndThen(Collectors.toList(),
24 | e -> e.stream().sorted().collect(Collectors.toList())))));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/resources/calculator-core.properties:
--------------------------------------------------------------------------------
1 | precompute.path=com.gch.discount.demo.biz
--------------------------------------------------------------------------------