|
1
|
+/**
|
|
2
|
+ * Copyright © 2016-2021 The Thingsboard Authors
|
|
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
|
+package org.thingsboard.server.dao.attributes;
|
|
17
|
+
|
|
18
|
+import com.google.common.util.concurrent.Futures;
|
|
19
|
+import com.google.common.util.concurrent.ListenableFuture;
|
|
20
|
+import com.google.common.util.concurrent.MoreExecutors;
|
|
21
|
+import lombok.extern.slf4j.Slf4j;
|
|
22
|
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
|
23
|
+import org.springframework.cache.Cache;
|
|
24
|
+import org.springframework.cache.CacheManager;
|
|
25
|
+import org.springframework.context.annotation.Primary;
|
|
26
|
+import org.springframework.stereotype.Service;
|
|
27
|
+import org.thingsboard.server.common.data.EntityType;
|
|
28
|
+import org.thingsboard.server.common.data.id.DeviceProfileId;
|
|
29
|
+import org.thingsboard.server.common.data.id.EntityId;
|
|
30
|
+import org.thingsboard.server.common.data.id.TenantId;
|
|
31
|
+import org.thingsboard.server.common.data.kv.AttributeKvEntry;
|
|
32
|
+import org.thingsboard.server.common.data.kv.KvEntry;
|
|
33
|
+import org.thingsboard.server.common.stats.DefaultCounter;
|
|
34
|
+import org.thingsboard.server.common.stats.StatsFactory;
|
|
35
|
+import org.thingsboard.server.dao.service.Validator;
|
|
36
|
+
|
|
37
|
+import java.util.ArrayList;
|
|
38
|
+import java.util.Collection;
|
|
39
|
+import java.util.HashMap;
|
|
40
|
+import java.util.List;
|
|
41
|
+import java.util.Map;
|
|
42
|
+import java.util.Objects;
|
|
43
|
+import java.util.Optional;
|
|
44
|
+import java.util.stream.Collectors;
|
|
45
|
+
|
|
46
|
+import static org.thingsboard.server.common.data.CacheConstants.ATTRIBUTES_CACHE;
|
|
47
|
+import static org.thingsboard.server.dao.attributes.AttributeUtils.validate;
|
|
48
|
+
|
|
49
|
+@Service
|
|
50
|
+@ConditionalOnProperty(prefix = "cache.attributes", value = "enabled", havingValue = "true")
|
|
51
|
+@Primary
|
|
52
|
+@Slf4j
|
|
53
|
+public class CachedAttributesService implements AttributesService {
|
|
54
|
+ private static final String STATS_NAME = "attributes.cache";
|
|
55
|
+
|
|
56
|
+ private final AttributesDao attributesDao;
|
|
57
|
+ private final Cache attributesCache;
|
|
58
|
+
|
|
59
|
+ private final DefaultCounter hitCounter;
|
|
60
|
+ private final DefaultCounter missCounter;
|
|
61
|
+
|
|
62
|
+ public CachedAttributesService(AttributesDao attributesDao,
|
|
63
|
+ CacheManager cacheManager,
|
|
64
|
+ StatsFactory statsFactory) {
|
|
65
|
+ this.attributesDao = attributesDao;
|
|
66
|
+ this.attributesCache = cacheManager.getCache(ATTRIBUTES_CACHE);
|
|
67
|
+
|
|
68
|
+ this.hitCounter = statsFactory.createDefaultCounter(STATS_NAME, "result", "hit");
|
|
69
|
+ this.missCounter = statsFactory.createDefaultCounter(STATS_NAME, "result", "miss");
|
|
70
|
+ }
|
|
71
|
+
|
|
72
|
+ @Override
|
|
73
|
+ public ListenableFuture<Optional<AttributeKvEntry>> find(TenantId tenantId, EntityId entityId, String scope, String attributeKey) {
|
|
74
|
+ validate(entityId, scope);
|
|
75
|
+ Validator.validateString(attributeKey, "Incorrect attribute key " + attributeKey);
|
|
76
|
+
|
|
77
|
+ AttributeCacheKey attributeCacheKey = new AttributeCacheKey(scope, entityId, attributeKey);
|
|
78
|
+ Cache.ValueWrapper cachedAttributeValue = attributesCache.get(attributeCacheKey);
|
|
79
|
+ if (cachedAttributeValue != null) {
|
|
80
|
+ hitCounter.increment();
|
|
81
|
+ AttributeKvEntry cachedAttributeKvEntry = (AttributeKvEntry) cachedAttributeValue.get();
|
|
82
|
+ return Futures.immediateFuture(Optional.ofNullable(cachedAttributeKvEntry));
|
|
83
|
+ } else {
|
|
84
|
+ missCounter.increment();
|
|
85
|
+ ListenableFuture<Optional<AttributeKvEntry>> result = attributesDao.find(tenantId, entityId, scope, attributeKey);
|
|
86
|
+ return Futures.transform(result, foundAttrKvEntry -> {
|
|
87
|
+ // TODO: think if it's a good idea to store 'empty' attributes
|
|
88
|
+ attributesCache.put(attributeKey, foundAttrKvEntry.orElse(null));
|
|
89
|
+ return foundAttrKvEntry;
|
|
90
|
+ }, MoreExecutors.directExecutor());
|
|
91
|
+ }
|
|
92
|
+ }
|
|
93
|
+
|
|
94
|
+ @Override
|
|
95
|
+ public ListenableFuture<List<AttributeKvEntry>> find(TenantId tenantId, EntityId entityId, String scope, Collection<String> attributeKeys) {
|
|
96
|
+ validate(entityId, scope);
|
|
97
|
+ attributeKeys.forEach(attributeKey -> Validator.validateString(attributeKey, "Incorrect attribute key " + attributeKey));
|
|
98
|
+
|
|
99
|
+ Map<String, Cache.ValueWrapper> wrappedCachedAttributes = findCachedAttributes(entityId, scope, attributeKeys);
|
|
100
|
+
|
|
101
|
+ List<AttributeKvEntry> cachedAttributes = wrappedCachedAttributes.values().stream()
|
|
102
|
+ .map(wrappedCachedAttribute -> (AttributeKvEntry) wrappedCachedAttribute.get())
|
|
103
|
+ .filter(Objects::nonNull)
|
|
104
|
+ .collect(Collectors.toList());
|
|
105
|
+ if (wrappedCachedAttributes.size() == attributeKeys.size()) {
|
|
106
|
+ return Futures.immediateFuture(cachedAttributes);
|
|
107
|
+ }
|
|
108
|
+
|
|
109
|
+ ArrayList<String> notFoundAttributeKeys = new ArrayList<>(attributeKeys);
|
|
110
|
+ notFoundAttributeKeys.removeAll(wrappedCachedAttributes.keySet());
|
|
111
|
+
|
|
112
|
+ ListenableFuture<List<AttributeKvEntry>> result = attributesDao.find(tenantId, entityId, scope, notFoundAttributeKeys);
|
|
113
|
+ return Futures.transform(result, foundInDbAttributes -> {
|
|
114
|
+ return mergeDbAndCacheAttributes(entityId, scope, cachedAttributes, notFoundAttributeKeys, foundInDbAttributes);
|
|
115
|
+ }, MoreExecutors.directExecutor());
|
|
116
|
+
|
|
117
|
+ }
|
|
118
|
+
|
|
119
|
+ private Map<String, Cache.ValueWrapper> findCachedAttributes(EntityId entityId, String scope, Collection<String> attributeKeys) {
|
|
120
|
+ Map<String, Cache.ValueWrapper> cachedAttributes = new HashMap<>();
|
|
121
|
+ for (String attributeKey : attributeKeys) {
|
|
122
|
+ Cache.ValueWrapper cachedAttributeValue = attributesCache.get(new AttributeCacheKey(scope, entityId, attributeKey));
|
|
123
|
+ if (cachedAttributeValue != null) {
|
|
124
|
+ hitCounter.increment();
|
|
125
|
+ cachedAttributes.put(attributeKey, cachedAttributeValue);
|
|
126
|
+ } else {
|
|
127
|
+ missCounter.increment();
|
|
128
|
+ }
|
|
129
|
+ }
|
|
130
|
+ return cachedAttributes;
|
|
131
|
+ }
|
|
132
|
+
|
|
133
|
+ private List<AttributeKvEntry> mergeDbAndCacheAttributes(EntityId entityId, String scope, List<AttributeKvEntry> cachedAttributes, ArrayList<String> notFoundAttributeKeys, List<AttributeKvEntry> foundInDbAttributes) {
|
|
134
|
+ for (AttributeKvEntry foundInDbAttribute : foundInDbAttributes) {
|
|
135
|
+ AttributeCacheKey attributeCacheKey = new AttributeCacheKey(scope, entityId, foundInDbAttribute.getKey());
|
|
136
|
+ attributesCache.put(attributeCacheKey, foundInDbAttribute);
|
|
137
|
+ notFoundAttributeKeys.remove(foundInDbAttribute.getKey());
|
|
138
|
+ }
|
|
139
|
+ for (String key : notFoundAttributeKeys){
|
|
140
|
+ attributesCache.put(new AttributeCacheKey(scope, entityId, key), null);
|
|
141
|
+ }
|
|
142
|
+ List<AttributeKvEntry> mergedAttributes = new ArrayList<>(cachedAttributes);
|
|
143
|
+ mergedAttributes.addAll(foundInDbAttributes);
|
|
144
|
+ return mergedAttributes;
|
|
145
|
+ }
|
|
146
|
+
|
|
147
|
+ @Override
|
|
148
|
+ public ListenableFuture<List<AttributeKvEntry>> findAll(TenantId tenantId, EntityId entityId, String scope) {
|
|
149
|
+ validate(entityId, scope);
|
|
150
|
+ return attributesDao.findAll(tenantId, entityId, scope);
|
|
151
|
+ }
|
|
152
|
+
|
|
153
|
+ @Override
|
|
154
|
+ public List<String> findAllKeysByDeviceProfileId(TenantId tenantId, DeviceProfileId deviceProfileId) {
|
|
155
|
+ return attributesDao.findAllKeysByDeviceProfileId(tenantId, deviceProfileId);
|
|
156
|
+ }
|
|
157
|
+
|
|
158
|
+ @Override
|
|
159
|
+ public List<String> findAllKeysByEntityIds(TenantId tenantId, EntityType entityType, List<EntityId> entityIds) {
|
|
160
|
+ return attributesDao.findAllKeysByEntityIds(tenantId, entityType, entityIds);
|
|
161
|
+ }
|
|
162
|
+
|
|
163
|
+ @Override
|
|
164
|
+ public ListenableFuture<List<Void>> save(TenantId tenantId, EntityId entityId, String scope, List<AttributeKvEntry> attributes) {
|
|
165
|
+ validate(entityId, scope);
|
|
166
|
+ attributes.forEach(AttributeUtils::validate);
|
|
167
|
+
|
|
168
|
+ List<ListenableFuture<Void>> saveFutures = attributes.stream().map(attribute -> attributesDao.save(tenantId, entityId, scope, attribute)).collect(Collectors.toList());
|
|
169
|
+ ListenableFuture<List<Void>> future = Futures.allAsList(saveFutures);
|
|
170
|
+
|
|
171
|
+ // TODO: can do if (attributesCache.get() != null) attributesCache.put() instead, but will be more twice more requests to cache
|
|
172
|
+ List<String> attributeKeys = attributes.stream().map(KvEntry::getKey).collect(Collectors.toList());
|
|
173
|
+ future.addListener(() -> evictAttributesFromCache(tenantId, entityId, scope, attributeKeys), MoreExecutors.directExecutor());
|
|
174
|
+ return future;
|
|
175
|
+ }
|
|
176
|
+
|
|
177
|
+ @Override
|
|
178
|
+ public ListenableFuture<List<Void>> removeAll(TenantId tenantId, EntityId entityId, String scope, List<String> attributeKeys) {
|
|
179
|
+ validate(entityId, scope);
|
|
180
|
+ ListenableFuture<List<Void>> future = attributesDao.removeAll(tenantId, entityId, scope, attributeKeys);
|
|
181
|
+ future.addListener(() -> evictAttributesFromCache(tenantId, entityId, scope, attributeKeys), MoreExecutors.directExecutor());
|
|
182
|
+ return future;
|
|
183
|
+ }
|
|
184
|
+
|
|
185
|
+ private void evictAttributesFromCache(TenantId tenantId, EntityId entityId, String scope, List<String> attributeKeys) {
|
|
186
|
+ try {
|
|
187
|
+ for (String attributeKey : attributeKeys) {
|
|
188
|
+ attributesCache.evict(new AttributeCacheKey(scope, entityId, attributeKey));
|
|
189
|
+ }
|
|
190
|
+ } catch (Exception e) {
|
|
191
|
+ log.error("[{}][{}] Failed to remove values from cache.", tenantId, entityId, e);
|
|
192
|
+ }
|
|
193
|
+ }
|
|
194
|
+} |
...
|
...
|
|