redis管道技术pipeline一 ——api

import java.io.UnsupportedEncodingException;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
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.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 封装redis 缓存服务器服务接口 */
@Service(value = "redisService")
public class RedisServiceImpl implements RedisService {

    private static String redisCode = "utf-8";

    /**
     * @param key
     */
    public long del(final String... keys) {
        return redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                long result = 0;
                for (int i = 0; i < keys.length; i++) {
                    result = connection.del(keys[i].getBytes());
                }
                return result;
            }
        });
    }

    /**
     * @param key
     * @param value
     * @param liveTime
     */
    public void set(final byte[] key, final byte[] value, final long liveTime) {
        redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(key, value);
                if (liveTime > 0) {
                    connection.expire(key, liveTime);
                }
                return 1L;
            }
        });
    }

    /**
     * @param key
     * @param value
     * @param liveTime
     */
    public void set(String key, String value, long liveTime) {
        this.set(key.getBytes(), value.getBytes(), liveTime);
    }

    /**
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        this.set(key, value, 0L);
    }

    /**
     * @param key
     * @param value
     */
    public void set(byte[] key, byte[] value) {
        this.set(key, value, 0L);
    }

    /**
     * @param key
     * @return
     */
    public String get(final String key) {
        return redisTemplate.execute(new RedisCallback() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                try {
                    return new String(connection.get(key.getBytes()), redisCode);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return "";
            }
        });
    }

    /**
     * @param pattern
     * @return
     */
    public Setkeys(String pattern) {
        return redisTemplate.keys(pattern);

    }

    /**
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.execute(new RedisCallback() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.exists(key.getBytes());
            }
        });
    }

    /**
     * @return
     */
    public String flushDB() {
        return redisTemplate.execute(new RedisCallback() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushDb();
                return "ok";
            }
        });
    }

    /**
     * @return
     */
    public long dbSize() {
        return redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.dbSize();
            }
        });
    }

    /**
     * @return
     */
    public String ping() {
        return redisTemplate.execute(new RedisCallback() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {

                return connection.ping();
            }
        });
    }


}

测试:

package com.aswatson.applicaton;

import com.alibaba.fastjson.JSONObject;
import com.aswatson.client.ChangeDataListener;
import com.aswatson.csc.member.vo.OptionVO;
import com.aswatson.csc.member.vo.ResponseMessages;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.RedisTemplate;

import java.util.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class PipelineRedisController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ChangeDataListener changeDataListener;

//    @RequestMapping(value = "/testException" )
//    public void testException(){
//        changeDataListener.processChangeData();
//    }

    /**
     * redis 批量操作其中一种方式
     * redis pipeline 管道技术
     */
    @RequestMapping(value = "/redisPipeline" )
    public void redisPipeline(){

        List<Object> list = new ArrayList();
        JSONObject json = new JSONObject();
        json.put("rr", "值rr");
        list.add(json);

        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                connection.openPipeline();
                Map<byte[],byte[]> tuple = new HashMap<>();

                for (Object obj : list) {
                    JSONObject objName = JSONObject.parseObject(obj.toString());
                    Set<String> keys = objName.keySet();
                    for (String redisKey : keys) {
                        String value = objName.get(redisKey).toString();
                        tuple.put(redisKey.getBytes(), value.getBytes());
                        //设置过期时间
                        connection.mSet(tuple);
                        connection.expire(redisKey.getBytes(), 5);
                        System.out.println("set time=" + LocalDateTime.now());
                    }
                }
                connection.closePipeline();
                return null;
            }
        });
    }

    @GetMapping("/testValue/{key}")
    public Object getMemberOptionType(@PathVariable(value="key") String key) {
        System.out.println("get time=" + LocalDateTime.now() + "/" + testExpeireTime(key));
        return LocalDateTime.now() + "/" + testExpeireTime(key);
    }


    private Object testExpeireTime(String key) {

        return redisTemplate.execute(new RedisCallback() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                try {
                    return new String(connection.get(key.getBytes()), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return "";
            }
        });
    }



    //    public static void main(String[] args) {
//
//        List<Object> list = new ArrayList();
//        JSONObject json = new JSONObject();
//        json.put("kk", "测试kk");
//        json.put("tt", "测试tt");
//        list.add(json);
//        for (Object obj : list) {
//            System.out.println(obj);
//            String [] arr = obj.toString().replace("{", "").replace("}", "").split("=");
//            System.out.println(Arrays.asList(arr).get(0));
//            System.out.println(Arrays.asList(arr).get(1));
//
//            JSONObject objName = JSONObject.parseObject(obj.toString());
//            System.out.println(objName.get("kk"));
//        }
//    }


    //    public static void main(String[] args) {
    //
    //        List list = new ArrayList();
    //        JSONObject json = new JSONObject();
    //        json.put("kk", "测试kk");
    //        list.add(json);
    //        for (Object obj : list) {
    //            //用json
    //            JSONObject objName = JSONObject.parseObject(obj.toString());
    //            Set<String> keys = objName.keySet();
    //            for (String redisKey : keys) {
    //                System.out.println(redisKey);
    //                System.out.println(objName.get(redisKey));
    //            }
    //
    //        }
    //    }


}
原文地址:https://www.cnblogs.com/lgg20/p/14247109.html