package com.zhiqiyun.open.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhiqiyun.open.config.RedisKeys;
import com.zhiqiyun.open.core.mapper.AppKeyInfoMapper;
import com.zhiqiyun.open.core.models.app.AppKeyInfo;
import com.zhiqiyun.open.core.service.AppKeyInfoService;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AppKeyInfoServiceImpl extends ServiceImpl<AppKeyInfoMapper, AppKeyInfo> implements AppKeyInfoService {

    @Resource
    private RedisTemplate<String, AppKeyInfo> redisTemplate;

    @Override
    public AppKeyInfo findByAppKey(String appKey) {
        String redisKey = String.format(RedisKeys.APP_KEY_INFO, appKey);

        BoundValueOperations<String, AppKeyInfo> boundValueOperations = this.redisTemplate.boundValueOps(redisKey);
        AppKeyInfo appKeyInfo = boundValueOperations.get();
        if (appKeyInfo == null) {
            appKeyInfo = this.baseMapper.selectById(appKey);
            if (appKeyInfo != null) {
                boundValueOperations.set(appKeyInfo);
            }
        }
        return appKeyInfo;
    }

    @Override
    public void refreshCache(String appKey) {
        String redisKey = String.format(RedisKeys.APP_KEY_INFO, appKey);
        this.redisTemplate.delete(redisKey);
    }
}
