|
1 | 1 | package com.wego.httpcache.dao.impl.guava;
|
2 | 2 |
|
3 |
| -import com.fasterxml.jackson.core.JsonProcessingException; |
4 |
| -import com.fasterxml.jackson.databind.DeserializationFeature; |
5 |
| -import com.fasterxml.jackson.databind.ObjectMapper; |
6 |
| -import com.fasterxml.jackson.databind.SerializationFeature; |
7 | 3 | import com.google.common.cache.Cache;
|
8 | 4 | import com.google.common.cache.CacheBuilder;
|
9 | 5 | import com.wego.httpcache.dao.CachedResponseDao;
|
|
13 | 9 |
|
14 | 10 | public class GuavaCachedResponseImpl implements CachedResponseDao {
|
15 | 11 | private static final long CACHE_TTL = 30;
|
16 |
| - private static final Cache<String, String> CACHE = |
| 12 | + private static final Cache<String, CachedResponseEntity> CACHE = |
17 | 13 | CacheBuilder.newBuilder().expireAfterWrite(CACHE_TTL, TimeUnit.MINUTES).build();
|
18 | 14 |
|
19 |
| - private static final ObjectMapper OBJECT_MAPPER = |
20 |
| - new ObjectMapper() |
21 |
| - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) |
22 |
| - .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); |
23 |
| - |
24 | 15 | @Override
|
25 | 16 | public CachedResponseEntity save(CachedResponseEntity cachedResponseEntity, long ttl) {
|
26 |
| - String jsonEntity = null; |
27 |
| - try { |
28 |
| - jsonEntity = OBJECT_MAPPER.writeValueAsString(cachedResponseEntity); |
29 |
| - } catch (JsonProcessingException ex) { |
30 |
| - ex.printStackTrace(); |
31 |
| - } |
32 |
| - |
33 |
| - if (jsonEntity != null) { |
34 |
| - CACHE.put(cachedResponseEntity.getId(), jsonEntity); |
| 17 | + if (cachedResponseEntity != null) { |
| 18 | + CACHE.put(cachedResponseEntity.getId(), cachedResponseEntity); |
35 | 19 | }
|
36 | 20 |
|
37 | 21 | return cachedResponseEntity;
|
38 | 22 | }
|
39 | 23 |
|
40 | 24 | @Override
|
41 | 25 | public Optional<CachedResponseEntity> findById(String id) {
|
42 |
| - CachedResponseEntity cachedResponseEntity = null; |
43 |
| - String jsonEntity = CACHE.getIfPresent(id); |
44 |
| - |
45 |
| - if (jsonEntity != null) { |
46 |
| - try { |
47 |
| - cachedResponseEntity = OBJECT_MAPPER.readValue(jsonEntity, CachedResponseEntity.class); |
48 |
| - } catch (Exception ex) { |
49 |
| - ex.printStackTrace(); |
50 |
| - } |
51 |
| - } |
52 |
| - |
53 |
| - return Optional.ofNullable(cachedResponseEntity); |
| 26 | + return Optional.ofNullable(CACHE.getIfPresent(id)); |
54 | 27 | }
|
55 | 28 | }
|
0 commit comments