liulingling.177216
2024-08-26 349f1cfc5fa77fbc636d542df0d8050fddec48c2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package com.dingzhuo.compute.engine.actor.indexcalc;
 
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import akka.actor.UntypedAbstractActor;
import akka.cluster.sharding.ClusterSharding;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import com.dingzhuo.compute.engine.function.FunctionEngine;
import com.dingzhuo.compute.engine.message.calculation.LoadCalcIndexMessage;
import com.dingzhuo.compute.engine.message.calculation.UnloadCalcIndexMessage;
import com.dingzhuo.compute.engine.utils.ActorUtil;
import com.dingzhuo.energy.data.model.domain.IndexStorage;
import com.dingzhuo.energy.data.model.service.IIndexStorageService;
import com.greenpineyu.fel.parser.FelNode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import scala.concurrent.duration.Duration;
 
/**
 * @author fanxinfu
 */
@Component("loadIndexActor")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class LoadIndexActor extends UntypedAbstractActor {
 
  LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
  private final IIndexStorageService indexStorageService;
  public static final String ACTOR_NAME = "loadIndexActor";
  private Map<String, IndexStorage> loadedCalcIndex = new HashMap<>();
  private ActorSelection calculateActor;
 
  public LoadIndexActor(IIndexStorageService indexStorageService) {
    this.indexStorageService = indexStorageService;
  }
 
  @Override
  public void preStart() {
    calculateActor = getContext()
        .actorSelection(ActorUtil.getActorAddress(CalculationIndexActor.ACTOR_NAME));
    this.context().system().scheduler()
        .scheduleAtFixedRate(Duration.Zero(), Duration.create(5, TimeUnit.MINUTES), this.self(),
            Message.REFRESH, this.context().system().dispatcher(), null);
  }
 
  @Override
  public void onReceive(Object message) {
    if (message instanceof Message) {
      if (message == Message.REFRESH) {
        refreshIndex();
      } else {
        this.unhandled(message);
      }
    }
  }
 
  private void refreshIndex() {
    List<IndexStorage> indexStorages = indexStorageService.getAllCalcIndexStorage();
    List<IndexStorage> filterIndexStorageList = new ArrayList<>();
    indexStorages.forEach(indexStorage -> {
      try {
        if (StringUtils.isNotBlank(indexStorage.getCalcText())) {
          FelNode node = FunctionEngine.getInstance().parse(indexStorage.getCalcText());
          if (node != null && !node.getChildren().isEmpty()) {
            filterIndexStorageList.add(indexStorage);
          } else {
            log.error("ErrorIndex:" + indexStorage.getId() + ";" + indexStorage.getCalcText());
          }
        }
      } catch (Exception ex) {
        log.error("ErrorIndex:" + indexStorage.getId() + ";" + indexStorage.getCalcText());
      }
    });
 
    if (filterIndexStorageList.isEmpty()) {
      return;
    }
 
    Map<String, IndexStorage> newCalcIndex = filterIndexStorageList.stream()
        .collect(Collectors.toMap(IndexStorage::getId, indexStorage -> indexStorage));
    Set<String> needInstall = new HashSet<>();
    Set<String> needUninstall = new HashSet<>();
 
    loadedCalcIndex.forEach((id, indexStorage) -> {
      if (!newCalcIndex.containsKey(id)) {
        needUninstall.add(id);
      } else {
        Date nowUpdate = newCalcIndex.get(id).getUpdateTime();
        Date lastUpdate = indexStorage.getUpdateTime();
        if (lastUpdate != null && nowUpdate != null && lastUpdate.after(nowUpdate)) {
          needUninstall.add(id);
          needInstall.add(id);
        }
      }
    });
 
    newCalcIndex.forEach((id, indexStorage) -> {
      if (!loadedCalcIndex.containsKey(id)) {
        needInstall.add(id);
      }
    });
 
    needUninstall.forEach(id -> {
      IndexStorage indexStorage = loadedCalcIndex.get(id);
      loadedCalcIndex.remove(id);
      calculateActor
          .tell(new UnloadCalcIndexMessage(ActorUtil.buildActorId(indexStorage)), getSelf());
    });
 
    needInstall.forEach(id -> {
      IndexStorage indexStorage = newCalcIndex.get(id);
      loadedCalcIndex.put(id, indexStorage);
      calculateActor.tell(new LoadCalcIndexMessage(indexStorage), getSelf());
    });
  }
 
  public enum Message {
    /**
     * 检测指标
     */
    REFRESH
  }
}