DictionaryServiceImpl.java 2.15 KB
package vion.service.impl;

import com.github.yulichang.base.MPJBaseServiceImpl;
import io.github.linpeilie.Converter;
import lombok.RequiredArgsConstructor;
import org.dromara.hutool.core.lang.Opt;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import vion.constant.RedisKeyEnum;
import vion.dto.DictionaryDTO;
import vion.mapper.DictionaryMapper;
import vion.model.Dictionary;
import vion.service.IDictionaryService;

import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DictionaryServiceImpl extends MPJBaseServiceImpl<DictionaryMapper, Dictionary> implements IDictionaryService {

    private final RedissonClient redissonClient;
    private final Converter converter;

    @Override
    public String save(DictionaryDTO data) {
        Dictionary dictionary = converter.convert(data, Dictionary.class);
        redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.getValByKey(dictionary.getType()))
                .put(dictionary.getKey(), dictionary.getValue());
        return this.save(dictionary) ? "成功" : "失败";
    }

    @Override
    public String update(DictionaryDTO data) {
        Dictionary dictionary = converter.convert(data, Dictionary.class);
        redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.getValByKey(dictionary.getType()))
                .put(dictionary.getKey(), dictionary.getValue());
        return this.updateById(dictionary) ? "成功" : "失败";
    }

    @Override
    public String remove(Long id, DictionaryDTO data) {
        redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.getValByKey(data.getType()))
                .remove(data.getKey());
        return this.removeById(id) ? "成功" : "失败";
    }

    @Override
    public void syncDict() {
        Opt.ofEmptyAble(this.list())
                .map(l -> l.stream().collect(Collectors.groupingBy(Dictionary::getType, Collectors.toMap(Dictionary::getKey, Dictionary::getValue))))
                .ifPresent(m -> m.forEach((type, map) -> redissonClient.getMap(RedisKeyEnum.DICT_PREFIX.getVal() + RedisKeyEnum.getValByKey(type)).putAll(map)));
    }
}