Redis API 必杀解读:引入RedisTemplate

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: 题记在工作和学习中啊,比如说JAVA开发,要使用Redis,首先要引入一个RedisTemplate类. 在此,将所有的方法都已经注释出来了.

题记

在工作和学习中啊,比如说JAVA开发,要使用Redis,首先要引入一个RedisTemplate类.
在此,将所有的方法都已经注释出来了.

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.data.redis.core;

import java.io.Closeable;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.data.redis.core.query.QueryUtils;
import org.springframework.data.redis.core.query.SortQuery;
import org.springframework.data.redis.core.script.DefaultScriptExecutor;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.script.ScriptExecutor;
import org.springframework.data.redis.core.types.RedisClientInfo;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationUtils;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware {
    private boolean enableTransactionSupport = false;
    private boolean exposeConnection = false;
    private boolean initialized = false;
    private boolean enableDefaultSerializer = true;
    private RedisSerializer<?> defaultSerializer;
    private ClassLoader classLoader;
    private RedisSerializer keySerializer = null;
    private RedisSerializer valueSerializer = null;
    private RedisSerializer hashKeySerializer = null;
    private RedisSerializer hashValueSerializer = null;
    private RedisSerializer<String> stringSerializer = new StringRedisSerializer();
    private ScriptExecutor<K> scriptExecutor;
    private ValueOperations<K, V> valueOps;
    private ListOperations<K, V> listOps;
    private SetOperations<K, V> setOps;
    private ZSetOperations<K, V> zSetOps;
    private GeoOperations<K, V> geoOps;
    private HyperLogLogOperations<K, V> hllOps;

    public RedisTemplate() {
    }

    //afterPropertiesSet (初始化操作)加载配置后执行
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        boolean defaultUsed = false;
        //serializer 序列化
        if (this.defaultSerializer == null) {
            this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
        }
        //enable 使能够,提供做…的权利[措施]; 使可能; 授予权利或方法;
        if (this.enableDefaultSerializer) {
            if (this.keySerializer == null) {
                this.keySerializer = this.defaultSerializer;
                defaultUsed = true;
            }

            if (this.valueSerializer == null) {
                this.valueSerializer = this.defaultSerializer;
                defaultUsed = true;
            }

            if (this.hashKeySerializer == null) {
                this.hashKeySerializer = this.defaultSerializer;
                defaultUsed = true;
            }

            if (this.hashValueSerializer == null) {
                this.hashValueSerializer = this.defaultSerializer;
                defaultUsed = true;
            }
        }

        if (this.enableDefaultSerializer && defaultUsed) {
            Assert.notNull(this.defaultSerializer, "default serializer null and not all serializers initialized");
        }

        //script脚本
        //Executor 遗嘱执行人; 执行者; 实行者;
        if (this.scriptExecutor == null) {
            this.scriptExecutor = new DefaultScriptExecutor(this);
        }
        //初始化完成
        this.initialized = true;
    }

    //execute 执行   exposeConnection暴露连接
    public <T> T execute(RedisCallback<T> action) {
        return this.execute(action, this.isExposeConnection());
    }

    public <T> T execute(RedisCallback<T> action, boolean exposeConnection) {
        return this.execute(action, exposeConnection, false);
    }

    //pipeline 管道
    public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {
        Assert.isTrue(this.initialized, "template not initialized; call afterPropertiesSet() before using it");
        Assert.notNull(action, "Callback object must not be null");
        RedisConnectionFactory factory = this.getConnectionFactory();
        RedisConnection conn = null;

        Object var11;
        try {
            //enableTransactionSupport 是否支持事务
            if (this.enableTransactionSupport) {
                conn = RedisConnectionUtils.bindConnection(factory, this.enableTransactionSupport);
            } else {
                conn = RedisConnectionUtils.getConnection(factory);
            }

            //现存的; 目前的;
            boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);
            RedisConnection connToUse = this.preProcessConnection(conn, existingConnection);
            boolean pipelineStatus = connToUse.isPipelined();
            if (pipeline && !pipelineStatus) {
                connToUse.openPipeline();
            }

            RedisConnection connToExpose = exposeConnection ? connToUse : this.createRedisConnectionProxy(connToUse);
            T result = action.doInRedis(connToExpose);
            if (pipeline && !pipelineStatus) {
                connToUse.closePipeline();
            }

            var11 = this.postProcessResult(result, connToUse, existingConnection);
        } finally {
            RedisConnectionUtils.releaseConnection(conn, factory);
        }

        return var11;
    }

    public <T> T execute(SessionCallback<T> session) {
        Assert.isTrue(this.initialized, "template not initialized; call afterPropertiesSet() before using it");
        Assert.notNull(session, "Callback object must not be null");
        RedisConnectionFactory factory = this.getConnectionFactory();
        RedisConnectionUtils.bindConnection(factory, this.enableTransactionSupport);

        Object var3;
        try {
            var3 = session.execute(this);
        } finally {
            RedisConnectionUtils.unbindConnection(factory);
        }

        return var3;
    }

    //executePipelined 执行管道
    public List<Object> executePipelined(SessionCallback<?> session) {
        return this.executePipelined(session, this.valueSerializer);
    }

    public List<Object> executePipelined(final SessionCallback<?> session, final RedisSerializer<?> resultSerializer) {
        Assert.isTrue(this.initialized, "template not initialized; call afterPropertiesSet() before using it");
        Assert.notNull(session, "Callback object must not be null");
        RedisConnectionFactory factory = this.getConnectionFactory();
        RedisConnectionUtils.bindConnection(factory, this.enableTransactionSupport);

        List var4;
        try {
            var4 = (List)this.execute(new RedisCallback<List<Object>>() {
                public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
                    connection.openPipeline();
                    boolean pipelinedClosed = false;

                    List var5;
                    try {
                        Object result = RedisTemplate.this.executeSession(session);
                        if (result != null) {
                            throw new InvalidDataAccessApiUsageException("Callback cannot return a non-null value as it gets overwritten by the pipeline");
                        }

                        List<Object> closePipeline = connection.closePipeline();
                        pipelinedClosed = true;
                        var5 = RedisTemplate.this.deserializeMixedResults(closePipeline, resultSerializer, RedisTemplate.this.hashKeySerializer, RedisTemplate.this.hashValueSerializer);
                    } finally {
                        if (!pipelinedClosed) {
                            connection.closePipeline();
                        }

                    }

                    return var5;
                }
            });
        } finally {
            RedisConnectionUtils.unbindConnection(factory);
        }

        return var4;
    }

    public List<Object> executePipelined(RedisCallback<?> action) {
        return this.executePipelined(action, this.valueSerializer);
    }

    public List<Object> executePipelined(final RedisCallback<?> action, final RedisSerializer<?> resultSerializer) {
        return (List)this.execute(new RedisCallback<List<Object>>() {
            public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
                connection.openPipeline();
                boolean pipelinedClosed = false;

                List var5;
                try {
                    Object result = action.doInRedis(connection);
                    if (result != null) {
                        throw new InvalidDataAccessApiUsageException("Callback cannot return a non-null value as it gets overwritten by the pipeline");
                    }

                    List<Object> closePipeline = connection.closePipeline();
                    pipelinedClosed = true;
                    var5 = RedisTemplate.this.deserializeMixedResults(closePipeline, resultSerializer, RedisTemplate.this.hashKeySerializer, RedisTemplate.this.hashValueSerializer);
                } finally {
                    if (!pipelinedClosed) {
                        connection.closePipeline();
                    }

                }

                return var5;
            }
        });
    }

    public <T> T execute(RedisScript<T> script, List<K> keys, Object... args) {
        return this.scriptExecutor.execute(script, keys, args);
    }

    public <T> T execute(RedisScript<T> script, RedisSerializer<?> argsSerializer, RedisSerializer<T> resultSerializer, List<K> keys, Object... args) {
        return this.scriptExecutor.execute(script, argsSerializer, resultSerializer, keys, args);
    }

    public <T extends Closeable> T executeWithStickyConnection(RedisCallback<T> callback) {
        Assert.isTrue(this.initialized, "template not initialized; call afterPropertiesSet() before using it");
        Assert.notNull(callback, "Callback object must not be null");
        RedisConnectionFactory factory = this.getConnectionFactory();
        RedisConnection connection = this.preProcessConnection(RedisConnectionUtils.doGetConnection(factory, true, false, false), false);
        return (Closeable)callback.doInRedis(connection);
    }

    //Session会话
    private Object executeSession(SessionCallback<?> session) {
        return session.execute(this);
    }

    //Proxy 代理服务器; 代表权; 代理人,代替物; 委托书;
    protected RedisConnection createRedisConnectionProxy(RedisConnection pm) {
        Class<?>[] ifcs = ClassUtils.getAllInterfacesForClass(pm.getClass(), this.getClass().getClassLoader());
        return (RedisConnection)Proxy.newProxyInstance(pm.getClass().getClassLoader(), ifcs, new CloseSuppressingInvocationHandler(pm));
    }

    protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
        return connection;
    }

    protected <T> T postProcessResult(T result, RedisConnection conn, boolean existingConnection) {
        return result;
    }

    public boolean isExposeConnection() {
        return this.exposeConnection;
    }

    public void setExposeConnection(boolean exposeConnection) {
        this.exposeConnection = exposeConnection;
    }

    //是否默认序列化
    public boolean isEnableDefaultSerializer() {
        return this.enableDefaultSerializer;
    }

    public void setEnableDefaultSerializer(boolean enableDefaultSerializer) {
        this.enableDefaultSerializer = enableDefaultSerializer;
    }

    public RedisSerializer<?> getDefaultSerializer() {
        return this.defaultSerializer;
    }

    public void setDefaultSerializer(RedisSerializer<?> serializer) {
        this.defaultSerializer = serializer;
    }

    public void setKeySerializer(RedisSerializer<?> serializer) {
        this.keySerializer = serializer;
    }

    public RedisSerializer<?> getKeySerializer() {
        return this.keySerializer;
    }

    public void setValueSerializer(RedisSerializer<?> serializer) {
        this.valueSerializer = serializer;
    }

    public RedisSerializer<?> getValueSerializer() {
        return this.valueSerializer;
    }

    public RedisSerializer<?> getHashKeySerializer() {
        return this.hashKeySerializer;
    }

    public void setHashKeySerializer(RedisSerializer<?> hashKeySerializer) {
        this.hashKeySerializer = hashKeySerializer;
    }

    public RedisSerializer<?> getHashValueSerializer() {
        return this.hashValueSerializer;
    }

    public void setHashValueSerializer(RedisSerializer<?> hashValueSerializer) {
        this.hashValueSerializer = hashValueSerializer;
    }

    public RedisSerializer<String> getStringSerializer() {
        return this.stringSerializer;
    }

    public void setStringSerializer(RedisSerializer<String> stringSerializer) {
        this.stringSerializer = stringSerializer;
    }

    public void setScriptExecutor(ScriptExecutor<K> scriptExecutor) {
        this.scriptExecutor = scriptExecutor;
    }

    private byte[] rawKey(Object key) {
        Assert.notNull(key, "non null key required");
        return this.keySerializer == null && key instanceof byte[] ? (byte[])((byte[])key) : this.keySerializer.serialize(key);
    }

    private byte[] rawString(String key) {
        return this.stringSerializer.serialize(key);
    }

    private byte[] rawValue(Object value) {
        return this.valueSerializer == null && value instanceof byte[] ? (byte[])((byte[])value) : this.valueSerializer.serialize(value);
    }

    private byte[][] rawKeys(Collection<K> keys) {
        byte[][] rawKeys = new byte[keys.size()][];
        int i = 0;

        Object key;
        for(Iterator var4 = keys.iterator(); var4.hasNext(); rawKeys[i++] = this.rawKey(key)) {
            key = var4.next();
        }

        return rawKeys;
    }

    //deserializeKey 反序列化
    private K deserializeKey(byte[] value) {
        return this.keySerializer != null ? this.keySerializer.deserialize(value) : value;
    }

    private List<Object> deserializeMixedResults(List<Object> rawValues, RedisSerializer valueSerializer, RedisSerializer hashKeySerializer, RedisSerializer hashValueSerializer) {
        if (rawValues == null) {
            return null;
        } else {
            List<Object> values = new ArrayList();
            Iterator var6 = rawValues.iterator();

            while(true) {
                while(var6.hasNext()) {
                    Object rawValue = var6.next();
                    if (rawValue instanceof byte[] && valueSerializer != null) {
                        values.add(valueSerializer.deserialize((byte[])((byte[])rawValue)));
                    } else if (rawValue instanceof List) {
                        values.add(this.deserializeMixedResults((List)rawValue, valueSerializer, hashKeySerializer, hashValueSerializer));
                    } else if (rawValue instanceof Set && !((Set)rawValue).isEmpty()) {
                        values.add(this.deserializeSet((Set)rawValue, valueSerializer));
                    } else if (rawValue instanceof Map && !((Map)rawValue).isEmpty() && ((Map)rawValue).values().iterator().next() instanceof byte[]) {
                        values.add(SerializationUtils.deserialize((Map)rawValue, hashKeySerializer, hashValueSerializer));
                    } else {
                        values.add(rawValue);
                    }
                }

                return values;
            }
        }
    }

    private Set<?> deserializeSet(Set rawSet, RedisSerializer valueSerializer) {
        if (rawSet.isEmpty()) {
            return rawSet;
        } else {
            Object setValue = rawSet.iterator().next();
            if (setValue instanceof byte[] && valueSerializer != null) {
                return SerializationUtils.deserialize(rawSet, valueSerializer);
            } else {
                return setValue instanceof Tuple ? this.convertTupleValues(rawSet, valueSerializer) : rawSet;
            }
        }
    }

    //拼装数组值
    private Set<TypedTuple<V>> convertTupleValues(Set<Tuple> rawValues, RedisSerializer valueSerializer) {
        Set<TypedTuple<V>> set = new LinkedHashSet(rawValues.size());

        Tuple rawValue;
        Object value;
        for(Iterator var4 = rawValues.iterator(); var4.hasNext(); set.add(new DefaultTypedTuple(value, rawValue.getScore()))) {
            rawValue = (Tuple)var4.next();
            value = rawValue.getValue();
            if (valueSerializer != null) {
                value = valueSerializer.deserialize(rawValue.getValue());
            }
        }

        return set;
    }

    public List<Object> exec() {
        List<Object> results = this.execRaw();
        return this.getConnectionFactory().getConvertPipelineAndTxResults() ? this.deserializeMixedResults(results, this.valueSerializer, this.hashKeySerializer, this.hashValueSerializer) : results;
    }

    public List<Object> exec(RedisSerializer<?> valueSerializer) {
        return this.deserializeMixedResults(this.execRaw(), valueSerializer, valueSerializer, valueSerializer);
    }

    protected List<Object> execRaw() {
        return (List)this.execute(new RedisCallback<List<Object>>() {
            public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.exec();
            }
        });
    }

    //删除,根据键删除值
    public void delete(K key) {
        final byte[] rawKey = this.rawKey(key);
        this.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) {
                connection.del(new byte[][]{rawKey});
                return null;
            }
        }, true);
    }

    //删除,根据键的集合,批量删除值
    public void delete(Collection<K> keys) {
        if (!CollectionUtils.isEmpty(keys)) {
            final byte[][] rawKeys = this.rawKeys(keys);
            this.execute(new RedisCallback<Object>() {
                public Object doInRedis(RedisConnection connection) {
                    connection.del(rawKeys);
                    return null;
                }
            }, true);
        }
    }

    //是否含有指定的键
    public Boolean hasKey(K key) {
        final byte[] rawKey = this.rawKey(key);
        return (Boolean)this.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) {
                return connection.exists(rawKey);
            }
        }, true);
    }

    //缓存是否过期
    //expire 期满; 文件、协议等(因到期而)失效; 断气; 逝世;
    public Boolean expire(K key, final long timeout, final TimeUnit unit) {
        final byte[] rawKey = this.rawKey(key);
        final long rawTimeout = TimeoutUtils.toMillis(timeout, unit);
        return (Boolean)this.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) {
                try {
                    return connection.pExpire(rawKey, rawTimeout);
                } catch (Exception var3) {
                    return connection.expire(rawKey, TimeoutUtils.toSeconds(timeout, unit));
                }
            }
        }, true);
    }

    public Boolean expireAt(K key, final Date date) {
        final byte[] rawKey = this.rawKey(key);
        return (Boolean)this.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) {
                try {
                    return connection.pExpireAt(rawKey, date.getTime());
                } catch (Exception var3) {
                    return connection.expireAt(rawKey, date.getTime() / 1000L);
                }
            }
        }, true);
    }

    //订阅发布
    public void convertAndSend(String channel, Object message) {
        Assert.hasText(channel, "a non-empty channel is required");
        final byte[] rawChannel = this.rawString(channel);
        final byte[] rawMessage = this.rawValue(message);
        this.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) {
                connection.publish(rawChannel, rawMessage);
                return null;
            }
        }, true);
    }

    public Long getExpire(K key) {
        final byte[] rawKey = this.rawKey(key);
        return (Long)this.execute(new RedisCallback<Long>() {
            public Long doInRedis(RedisConnection connection) {
                return connection.ttl(rawKey);
            }
        }, true);
    }

    public Long getExpire(K key, final TimeUnit timeUnit) {
        final byte[] rawKey = this.rawKey(key);
        return (Long)this.execute(new RedisCallback<Long>() {
            public Long doInRedis(RedisConnection connection) {
                try {
                    return connection.pTtl(rawKey, timeUnit);
                } catch (Exception var3) {
                    return connection.ttl(rawKey, timeUnit);
                }
            }
        }, true);
    }

    public Set<K> keys(K pattern) {
        final byte[] rawKey = this.rawKey(pattern);
        Set<byte[]> rawKeys = (Set)this.execute(new RedisCallback<Set<byte[]>>() {
            public Set<byte[]> doInRedis(RedisConnection connection) {
                return connection.keys(rawKey);
            }
        }, true);
        return this.keySerializer != null ? SerializationUtils.deserialize(rawKeys, this.keySerializer) : rawKeys;
    }

    //持久化
    //persist:坚持; 存留; 固执; 继续存在;
    public Boolean persist(K key) {
        final byte[] rawKey = this.rawKey(key);
        return (Boolean)this.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) {
                return connection.persist(rawKey);
            }
        }, true);
    }

    //move移动
    public Boolean move(K key, final int dbIndex) {
        final byte[] rawKey = this.rawKey(key);
        return (Boolean)this.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) {
                return connection.move(rawKey, dbIndex);
            }
        }, true);
    }

    //获取随机key值
    public K randomKey() {
        byte[] rawKey = (byte[])this.execute(new RedisCallback<byte[]>() {
            public byte[] doInRedis(RedisConnection connection) {
                return connection.randomKey();
            }
        }, true);
        return this.deserializeKey(rawKey);
    }

    //key值重命名
    public void rename(K oldKey, K newKey) {
        final byte[] rawOldKey = this.rawKey(oldKey);
        final byte[] rawNewKey = this.rawKey(newKey);
        this.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) {
                connection.rename(rawOldKey, rawNewKey);
                return null;
            }
        }, true);
    }

    //如果没有就重命名
    //Absent 缺席的,不在场的; 缺少的,缺乏的; 不在意的,茫然的;
    public Boolean renameIfAbsent(K oldKey, K newKey) {
        final byte[] rawOldKey = this.rawKey(oldKey);
        final byte[] rawNewKey = this.rawKey(newKey);
        return (Boolean)this.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) {
                return connection.renameNX(rawOldKey, rawNewKey);
            }
        }, true);
    }

    //DataType类型的 类型
    public DataType type(K key) {
        final byte[] rawKey = this.rawKey(key);
        return (DataType)this.execute(new RedisCallback<DataType>() {
            public DataType doInRedis(RedisConnection connection) {
                return connection.type(rawKey);
            }
        }, true);
    }

    public byte[] dump(K key) {
        final byte[] rawKey = this.rawKey(key);
        return (byte[])this.execute(new RedisCallback<byte[]>() {
            public byte[] doInRedis(RedisConnection connection) {
                return connection.dump(rawKey);
            }
        }, true);
    }

    //restore 修复; 归还; 交还; 使恢复;
    public void restore(K key, final byte[] value, long timeToLive, TimeUnit unit) {
        final byte[] rawKey = this.rawKey(key);
        final long rawTimeout = TimeoutUtils.toMillis(timeToLive, unit);
        this.execute(new RedisCallback<Object>() {
            public Boolean doInRedis(RedisConnection connection) {
                connection.restore(rawKey, rawTimeout, value);
                return null;
            }
        }, true);
    }

    //multi 前缀
    public void multi() {
        this.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.multi();
                return null;
            }
        }, true);
    }

    //discard 丢弃,抛弃; 解雇; 出牌;
    public void discard() {
        this.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.discard();
                return null;
            }
        }, true);
    }

    //watch 注视,注意; 看守,监视; 守候(机会等); 密切注意
    public void watch(K key) {
        final byte[] rawKey = this.rawKey(key);
        this.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) {
                connection.watch(new byte[][]{rawKey});
                return null;
            }
        }, true);
    }

    public void watch(Collection<K> keys) {
        final byte[][] rawKeys = this.rawKeys(keys);
        this.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) {
                connection.watch(rawKeys);
                return null;
            }
        }, true);
    }

    public void unwatch() {
        this.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.unwatch();
                return null;
            }
        }, true);
    }

    //sort 排序
    public List<V> sort(SortQuery<K> query) {
        return this.sort(query, this.valueSerializer);
    }

    public <T> List<T> sort(SortQuery<K> query, RedisSerializer<T> resultSerializer) {
        final byte[] rawKey = this.rawKey(query.getKey());
        final SortParameters params = QueryUtils.convertQuery(query, this.stringSerializer);
        List<byte[]> vals = (List)this.execute(new RedisCallback<List<byte[]>>() {
            public List<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.sort(rawKey, params);
            }
        }, true);
        return SerializationUtils.deserialize(vals, resultSerializer);
    }

    public <T> List<T> sort(SortQuery<K> query, BulkMapper<T, V> bulkMapper) {
        return this.sort(query, bulkMapper, this.valueSerializer);
    }

    public <T, S> List<T> sort(SortQuery<K> query, BulkMapper<T, S> bulkMapper, RedisSerializer<S> resultSerializer) {
        List<S> values = this.sort(query, resultSerializer);
        if (values != null && !values.isEmpty()) {
            int bulkSize = query.getGetPattern().size();
            List<T> result = new ArrayList(values.size() / bulkSize + 1);
            List<S> bulk = new ArrayList(bulkSize);
            Iterator var8 = values.iterator();

            while(var8.hasNext()) {
                S s = var8.next();
                bulk.add(s);
                if (bulk.size() == bulkSize) {
                    result.add(bulkMapper.mapBulk(Collections.unmodifiableList(bulk)));
                    bulk = new ArrayList(bulkSize);
                }
            }

            return result;
        } else {
            return Collections.emptyList();
        }
    }

    public Long sort(SortQuery<K> query, K storeKey) {
        final byte[] rawStoreKey = this.rawKey(storeKey);
        final byte[] rawKey = this.rawKey(query.getKey());
        final SortParameters params = QueryUtils.convertQuery(query, this.stringSerializer);
        return (Long)this.execute(new RedisCallback<Long>() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.sort(rawKey, params, rawStoreKey);
            }
        }, true);
    }

    //BoundValueOperations暂时不知道什么意思,可能是操作边界值
    //bound n界限,限制; 跃起; (球等的) 反跳 ,v缚; 给…划界,限制; 使弹回,使跳跃;
    public BoundValueOperations<K, V> boundValueOps(K key) {
        return new DefaultBoundValueOperations(key, this);
    }

    //操作值,描述具有简单值的条目
    public ValueOperations<K, V> opsForValue() {
        if (this.valueOps == null) {
            this.valueOps = new DefaultValueOperations(this);
        }

        return this.valueOps;
    }

    //操作集合,操作具有list值的条目
    public ListOperations<K, V> opsForList() {
        if (this.listOps == null) {
            this.listOps = new DefaultListOperations(this);
        }

        return this.listOps;
    }

    //以绑定指定key的方式,操作具有list的条目
    public BoundListOperations<K, V> boundListOps(K key) {
        return new DefaultBoundListOperations(key, this);
    }

    //以绑定指定key的方式,操作具有set的条目
    public BoundSetOperations<K, V> boundSetOps(K key) {
        return new DefaultBoundSetOperations(key, this);
    }

    //操作具有set值的条目
    public SetOperations<K, V> opsForSet() {
        if (this.setOps == null) {
            this.setOps = new DefaultSetOperations(this);
        }

        return this.setOps;
    }

    //以绑定指定key的方式,操作具有ZSet(排序的set)的条目
    public BoundZSetOperations<K, V> boundZSetOps(K key) {
        return new DefaultBoundZSetOperations(key, this);
    }

    //操作具有ZSet值(排序的set)的条目
    public ZSetOperations<K, V> opsForZSet() {
        if (this.zSetOps == null) {
            this.zSetOps = new DefaultZSetOperations(this);
        }

        return this.zSetOps;
    }

    //Geospatial 键操作
    public GeoOperations<K, V> opsForGeo() {
        if (this.geoOps == null) {
            this.geoOps = new DefaultGeoOperations(this);
        }

        return this.geoOps;
    }

    //Redis Geospatial 键绑定操作
    public BoundGeoOperations<K, V> boundGeoOps(K key) {
        return new DefaultBoundGeoOperations(key, this);
    }

    //操作Redis HyperLogLog类型数据,比如:pfadd,pfcount,...
    public HyperLogLogOperations<K, V> opsForHyperLogLog() {
        if (this.hllOps == null) {
            this.hllOps = new DefaultHyperLogLogOperations(this);
        }

        return this.hllOps;
    }

    //Redis Hash键绑定操作
    public <HK, HV> BoundHashOperations<K, HK, HV> boundHashOps(K key) {
        return new DefaultBoundHashOperations(key, this);
    }

    //操作Redis Hash类型数据
    public <HK, HV> HashOperations<K, HK, HV> opsForHash() {
        return new DefaultHashOperations(this);
    }

    //Cluster 群操作
    public ClusterOperations<K, V> opsForCluster() {
        return new DefaultClusterOperations(this);
    }

    public void killClient(final String host, final int port) {
        this.execute(new RedisCallback<Void>() {
            public Void doInRedis(RedisConnection connection) throws DataAccessException {
                connection.killClient(host, port);
                return null;
            }
        });
    }

    //获取redis客户端的集合
    public List<RedisClientInfo> getClientList() {
        return (List)this.execute(new RedisCallback<List<RedisClientInfo>>() {
            public List<RedisClientInfo> doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.getClientList();
            }
        });
    }

    //SLAVEOF 命令用于在 Redis 运行时动态地修改复制(replication)功能的行为
    public void slaveOf(final String host, final int port) {
        this.execute(new RedisCallback<Void>() {
            public Void doInRedis(RedisConnection connection) throws DataAccessException {
                connection.slaveOf(host, port);
                return null;
            }
        });
    }

    public void slaveOfNoOne() {
        this.execute(new RedisCallback<Void>() {
            public Void doInRedis(RedisConnection connection) throws DataAccessException {
                connection.slaveOfNoOne();
                return null;
            }
        });
    }

    public void setEnableTransactionSupport(boolean enableTransactionSupport) {
        this.enableTransactionSupport = enableTransactionSupport;
    }

    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }
}

这个类基本上就是所有的RedisTemplate.方法就可以用了哟。
例如:

/**保存成功后同步到缓存中**/
                redisTemplate.opsForList().rightPush(CachePrefix.CERT_BUNDLE_LIST + "_" + iosBundle.getCertId(), iosBundle.getId());
相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
6月前
|
JSON NoSQL Java
Redis入门到通关之Java客户端SpringDataRedis(RedisTemplate)
Redis入门到通关之Java客户端SpringDataRedis(RedisTemplate)
254 0
|
6月前
|
缓存 NoSQL Java
RedisTemplate操作Redis,这一篇文章就够了
redis是一款开源的Key-Value数据库,运行在内存中,由C语言编写。企业开发通常采用Redis来实现缓存。同类的产品还有memcache 、memcached 等。
787 1
|
2月前
|
JSON NoSQL Java
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)
这篇文章介绍了在Java中使用Redis客户端的几种方法,包括Jedis、SpringDataRedis和SpringBoot整合Redis的操作。文章详细解释了Jedis的基本使用步骤,Jedis连接池的创建和使用,以及在SpringBoot项目中如何配置和使用RedisTemplate和StringRedisTemplate。此外,还探讨了RedisTemplate序列化的两种实践方案,包括默认的JDK序列化和自定义的JSON序列化,以及StringRedisTemplate的使用,它要求键和值都必须是String类型。
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)
|
3月前
|
缓存 监控 NoSQL
【Azure Redis 缓存】Redis的监控方式? 是否有API接口调用来获取监控值
【Azure Redis 缓存】Redis的监控方式? 是否有API接口调用来获取监控值
|
5月前
|
监控 NoSQL Java
在 Spring Boot 中实现 Redis 的发布/订阅功能可以通过 RedisTemplate 和消息监听器来完成
在 Spring Boot 中实现 Redis 的发布/订阅功能可以通过 RedisTemplate 和消息监听器来完成
280 1
|
5月前
|
存储 监控 NoSQL
Redis系列学习文章分享---第十二篇(搭建哨兵集群+RedisTemplate连接哨兵+搭建分片集群+-散列插槽+集群伸缩 +故障转移+RedisTemplate访问分片集群)
Redis系列学习文章分享---第十二篇(搭建哨兵集群+RedisTemplate连接哨兵+搭建分片集群+-散列插槽+集群伸缩 +故障转移+RedisTemplate访问分片集群)
241 0
|
5月前
|
存储 NoSQL Java
Redis系列学习文章分享---第二篇(Redis快速入门之Java客户端--Jedis+连接池+SpringDataRedis+RedisTemplate+RedisSerializer+Hash)
Redis系列学习文章分享---第二篇(Redis快速入门之Java客户端--Jedis+连接池+SpringDataRedis+RedisTemplate+RedisSerializer+Hash)
260 0
|
6月前
|
NoSQL Java Redis
SpringBoot中操作RedisTemplate获取redis中以某些字符串为前缀的KEY列表
SpringBoot中操作RedisTemplate获取redis中以某些字符串为前缀的KEY列表
178 0
|
6月前
|
存储 JSON NoSQL
[Redis]——RedisTemplate的两种序列化方式
[Redis]——RedisTemplate的两种序列化方式
327 0
|
NoSQL Redis
RedisTemplate执行lua脚本在Redis集群模式下报错EvalSha is not supported in cluster environment.
RedisTemplate执行lua脚本在Redis集群模式下报错EvalSha is not supported in cluster environment.
297 0