CustomRedisUtil.java 1.5 KB
package com.skua.redis.util;

import com.skua.core.context.SpringContextUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author sonin
 * @date 2021/9/30 13:38
 */
@Component
public class CustomRedisUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void hset(String item, String key, Object val) {
        redisTemplate.opsForHash().put(item, key, val);
    }

    public void hsets(String item, Map<String, Object> map) {
        redisTemplate.opsForHash().putAll(item, map);
    }

    public String hget(String item, String key) {
        Object val = redisTemplate.opsForHash().get(item, key);
        return val == null ? null : val.toString();
    }

    public void hdel(String item, String key) {
        redisTemplate.opsForHash().delete(item, key);
    }

    public Object hget(String item, String key, String srcColumn, String targetColumn) {
        Object val = redisTemplate.opsForHash().get(item, key);
        if (val == null && (srcColumn != null && !"".equals(srcColumn))) {
            JdbcTemplate masterDB = (JdbcTemplate) SpringContextUtils.getBean("master");
            Map<String, Object> sqlMap = masterDB.queryForMap("select * from " + item + " where " + srcColumn + " = '" + key + "'");
            val = sqlMap.get(targetColumn);
            this.hset(item, key, val);
        }
        return val;
    }

}