Repository navigation
Expand file tree
/
Copy pathCacheSettingService.java
More file actions
71 lines (58 loc) · 2.12 KB
/
Copy pathCacheSettingService.java
File metadata and controls
71 lines (58 loc) · 2.12 KB
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
package com.raysmond.blog.services;
import com.raysmond.blog.models.Setting;
import com.raysmond.blog.repositories.SettingRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
/**
* @author Raysmond
*/
@Service
@Slf4j
@Transactional
public class CacheSettingService implements SettingService {
private SettingRepository settingRepository;
@Autowired
public CacheSettingService(SettingRepository settingRepository) {
this.settingRepository = settingRepository;
}
@Override
@Cacheable(value = "settingCache", key = "#key")
public Serializable get(String key) {
Setting setting = settingRepository.findByKey(key);
Serializable value = null;
try {
value = setting == null ? null : setting.getValue();
} catch (Exception ex) {
log.info("Cannot deserialize setting value with key = " + key);
}
log.info("Get setting " + key + " from database. Value = " + value);
return value;
}
@Override
@Cacheable(value = "settingCache", key = "#key")
public Serializable get(String key, Serializable defaultValue) {
Serializable value = get(key);
return value == null ? defaultValue : value;
}
@Override
@CacheEvict(value = "settingCache", key = "#key")
public void put(String key, Serializable value) {
log.info("Update setting " + key + " to database. Value = " + value);
Setting setting = settingRepository.findByKey(key);
if (setting == null) {
setting = new Setting();
setting.setKey(key);
}
try {
setting.setValue(value);
settingRepository.save(setting);
} catch (Exception ex) {
log.info("Cannot save setting value with type: " + value.getClass() + ". key = " + key);
}
}
}