SpringBoot Redis批量存取數據的操作

SpringBoot Redis批量存取數據

springboot中的redisTemplate封裝瞭redis批處理數據的接口,我們使用redisTemplate可以直接進行批量數據的get和set。

package com.huateng.applacation.service; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component; 
import java.util.List;
 
/**
 * @program: applacation
 * @description:
 * @author: daiwenlong
 * @create: 2019-01-24 13:26
 **/
@Component
public class RedisService {  
    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redisTemplate; 
    public void insertKey(List<String> keys, String value){ 
 
        //批量get數據
        List<Object> list = redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                for (String key : keys) {
                    connection.get(key.getBytes());
                }
                return null;
            }
        });
 
        //批量set數據
        redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                for (int i=0;i<keys.size();i++) {
                    connection.set(keys.get(i).getBytes(),value.getBytes());
                }
                return null;
            }
        }); 
    }
}

如果要設置 key 的過期時間,通過 setEx() 來做就可以瞭,過期時間單位是秒,相關代碼如下:

/**
 * 合同批量導入redis
 *
 * @param contractBOList
 * @param expire
 * @return com.openailab.oascloud.common.model.ResponseResult
 * @author zxzhang
 * @date 2019/10/14
 */
@Override
public void contractBatchSetRedis(String contractBOList, long expire) {
    List<ContractBO> contracts = JSONObject.parseArray(contractBOList, ContractBO.class);
    if (contracts == null || contracts.size() == 0) {
        return;
    }
    //批量set數據
    redisUtil.getRedisTemplate().executePipelined((RedisCallback<String>) connection -> {
        for (ContractBO contract : contracts) {
            connection.setEx((RedisPrefixConst.CONTRACT_PREFIX + contract.getBusinessCode() + RedisPrefixConst.UNDERLINE_SEPARATOR + contract.getContractNo()).getBytes(), expire, JSONObject.toJSONString(contract).getBytes());
        }
        return null;
    });
}
 
/**
 * 合同批量獲取redis
 *
 * @param contractBOList
 * @return java.lang.String
 * @author zxzhang
 * @date 2019/10/14
 */
@Override
public List<Object> contractBatchGetRedis(String contractBOList) {
    List<ContractBO> contracts = JSONObject.parseArray(contractBOList, ContractBO.class);
    if (contracts == null || contracts.size() == 0) {
        return null;
    }
    List<Object> list = redisUtil.getRedisTemplate().executePipelined((RedisCallback<String>) connection -> {
        for (ContractBO contract : contracts) {
            connection.get((RedisPrefixConst.CONTRACT_PREFIX + contract.getBusinessCode() + RedisPrefixConst.UNDERLINE_SEPARATOR + contract.getContractNo()).getBytes());
        }
        return null;
    });
    return list;
}

SpringBoot對redis批量存取介紹到此結束。

redisTemplate批量寫入數據

 /**
     * 批量寫入數據
     * @param objectMap
     * @return
     */
    public void saveMap(final Map<String,Object> objectMap) {
        //序列化成字節數組
        final Map<byte[],byte[]> byteMap=new HashMap<>();
        for(Map.Entry<String,Object> objectEntry:objectMap.entrySet()){
            String key=objectEntry.getKey();
            final byte[] keyBytes = redisTemplate.getStringSerializer().serialize(key);
            Object value=objectEntry.getValue();
            final byte[] valueBytes =SerializeUtil.serialize(value);
            byteMap.put(keyBytes,valueBytes);
        }
 
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) {
                try{
                    connection.mSet(byteMap);
                }catch (Exception ex){
                    log.error("redis批量寫入數據異常:"+ex.getMessage(),ex);
                }
                return null;
            }
        });
    }

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: