package com.elab.redis.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.elab.core.utils.RandomUtils;
import com.elab.redis.annotation.CacheLoopSubmit;
import com.elab.redis.redisson.doc.model.SomeObject;
import com.elab.redis.service.IDemoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ： lukx
 * @time ： 2020/7/9 - 20:31
 */
@Component
@CacheConfig(cacheNames = "")
public class DemoServiceImpl implements IDemoService {

    private volatile int count = 100;

    private Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);

    @Override
    @CacheLoopSubmit(unionKey = "[0]", cacheName = "demo", timeOut = 10)
    public String submit(String text) throws Exception {
        count--;
        Thread.sleep(500);
        logger.info(text + " 抢到一个资源 ， 资源池  " + count);

        return "lkx";
    }

    @Override
    @CacheLoopSubmit(unionKey = {"[0]{text},[0]{name}"}, cacheName = "demo", timeOut = 10)
    public String submit(SomeObject text) throws Exception {
        count--;
        Thread.sleep(500);
        logger.info(text + " 抢到一个资源 ， 资源池  " + count);
        return text.getText();
    }

    @Cacheable(cacheNames = "DemoServiceImpl", key = "':springCache'  +':'+#a0")
    public String springCache(String text) {
        String s = "xiong_" + RandomUtils.randomString(2);
        System.out.println("业务层获取参数值:" + text + " 返回值 : " + s);
        return s;
    }

    @Cacheable(cacheNames = "springcacheObject")
    public String springCacheObject(JSONObject jsonObject) {
        System.out.println("业务层获取参数值:" + jsonObject.toJSONString());
        return jsonObject.toJSONString();
    }

    @Override
    public String noCache(String text) {
        return null;
    }

    /**
     * 修改缓存
     *
     * @param key
     * @param value
     * @return
     */
    @Override
    @CachePut(cacheNames = "DemoServiceImpl", key = "'springCache' +'_'+#a0")
    public boolean put(String key, String value) {
        logger.info("数据库查询..");
        return false;
    }

    @Override
    @CacheEvict(cacheNames = "DemoServiceImpl", key = "'springCache' +'_'+#a0")
    public boolean del(String key, String value) {
        logger.info("执行数据库操作");
        return false;
    }
}
