CustomRedisUtil.java 1.8 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 Object hgetObj(String item, String key) {
        return redisTemplate.opsForHash().get(item, key);
    }

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

    public Object hget(String item, String key, String srcColumn, String targetColumn) {
        // 多个项目连的同一个redis,导致翻译dict出问题,现在改用直接查询
        Object val = "";
        try {
            JdbcTemplate masterDB = (JdbcTemplate) SpringContextUtils.getBean("master");
            Map<String, Object> sqlMap = masterDB.queryForMap("select * from " + item + " where " + srcColumn + " = '" + key + "'");
            val = sqlMap.get(targetColumn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return val;
    }

    public void deleteByPrex(String prex) {
        if (redisTemplate.hasKey(prex)) {
            redisTemplate.delete(prex);
        }
    }

}