|
|
@@ -0,0 +1,75 @@
|
|
|
+package com.tzld.piaoquan.ad.engine.commons.helper;
|
|
|
+
|
|
|
+import com.tzld.piaoquan.ad.engine.commons.redis.AlgorithmRedisHelper;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.apache.commons.lang3.tuple.Pair;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.scheduling.annotation.Scheduled;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import javax.annotation.PostConstruct;
|
|
|
+import java.util.Collections;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
+@Component
|
|
|
+public class LayerAgentFlowControlDataHelper {
|
|
|
+ @Autowired
|
|
|
+ protected AlgorithmRedisHelper algRedisHelper;
|
|
|
+
|
|
|
+ private static final String redisKey = "ad:engine:strategy:flowcontrol:layer_agent";
|
|
|
+ private static final String keyFormat = "%s:%s:%s";
|
|
|
+
|
|
|
+ private volatile static Map<String, Pair<Double, Double>> layerAgentMap = Collections.emptyMap();
|
|
|
+
|
|
|
+ // 服务启动时初始化数据
|
|
|
+ @PostConstruct
|
|
|
+ public void init() {
|
|
|
+ Map<String, Pair<Double, Double>> map = updateLayerAgentMap();
|
|
|
+ layerAgentMap = Collections.unmodifiableMap(map);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 每5分钟更新一次数据
|
|
|
+ @Scheduled(fixedRate = 5 * 60 * 1000)
|
|
|
+ public void scheduledUpdate() {
|
|
|
+ Map<String, Pair<Double, Double>> map = updateLayerAgentMap();
|
|
|
+ layerAgentMap = Collections.unmodifiableMap(map);
|
|
|
+ }
|
|
|
+
|
|
|
+ public static Pair<Double, Double> getWeight(String layer, String profession, String agentId) {
|
|
|
+ if (null != layerAgentMap) {
|
|
|
+ String key = String.format(keyFormat, layer, profession, agentId);
|
|
|
+ if (layerAgentMap.containsKey(key)) {
|
|
|
+ return layerAgentMap.get(key);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Pair<Double, Double>> updateLayerAgentMap() {
|
|
|
+ Map<String, Pair<Double, Double>> tmpLayerAgentMap = new HashMap<>();
|
|
|
+ try {
|
|
|
+ String value = algRedisHelper.get(redisKey);
|
|
|
+ if (null != value && !value.isEmpty()) {
|
|
|
+ String[] cells = value.split(",");
|
|
|
+ for (String cell : cells) {
|
|
|
+ String[] pair = cell.split("_");
|
|
|
+ if (2 == pair.length) {
|
|
|
+ String key = pair[0];
|
|
|
+ String[] values = pair[1].split(":");
|
|
|
+ if (2 == values.length) {
|
|
|
+ double cpmDiff = Double.parseDouble(values[0]);
|
|
|
+ double viewRate = Double.parseDouble(values[1]);
|
|
|
+ tmpLayerAgentMap.put(key, Pair.of(cpmDiff, viewRate));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ log.info("update layer agent flow control success size={}", tmpLayerAgentMap.size());
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("update layer agent flow control error", e);
|
|
|
+ }
|
|
|
+ return tmpLayerAgentMap;
|
|
|
+ }
|
|
|
+}
|