Redis-07-redis在SpringBoot中使用

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: SpringBoot提供了redis的starter

SpringBoot提供了redis的starter,集成的时候先在pom文件中引入依赖:

<!--redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>

版本的话,我创建项目用的是继承SpringBoot的parent,所以默认使用的就是parent的版本:2.3.1.RELEASE

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.1.RELEASE</version><relativePath/></parent>

在配置文件中配置redis连接信息:

spring.redis.host=${REDIS-HOST:127.0.0.1}
spring.redis.port=${REDIS-PORT:6379}
#spring.redis.password=${REDIS-PASW:Y4WyYKR5}
#第2个spring.redis.database=${REDIS-DB:1}
#连接池最大连接数(使用负值表示没有限制)spring.redis.jedis.pool.max-active=8#连接池中的最大空闲连接spring.redis.jedis.pool.max-idle=8#连接池中的最小空闲连接spring.redis.jedis.pool.min-idle=0#连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.jedis.pool.max-wait=3000#连接超时时间(毫秒)spring.redis.timeout=30000


在jar包中org.springframework.data.redis.core下的RedisTemplate<K, V>

我们主要是使用这个RedisTemplate<K, V>来操作redis数据库来进行交互。

//

// Source code recreated from a .class file by IntelliJ IDEA

// (powered by FernFlower decompiler)

//


packageorg.springframework.data.redis.core;
importjava.io.Closeable;
importjava.lang.reflect.Proxy;
importjava.util.ArrayList;
importjava.util.Collection;
importjava.util.Collections;
importjava.util.Date;
importjava.util.Iterator;
importjava.util.LinkedHashSet;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.concurrent.TimeUnit;
importorg.springframework.beans.factory.BeanClassLoaderAware;
importorg.springframework.dao.InvalidDataAccessApiUsageException;
importorg.springframework.data.redis.connection.DataType;
importorg.springframework.data.redis.connection.RedisConnection;
importorg.springframework.data.redis.connection.RedisConnectionFactory;
importorg.springframework.data.redis.connection.RedisKeyCommands;
importorg.springframework.data.redis.connection.RedisServerCommands;
importorg.springframework.data.redis.connection.RedisTxCommands;
importorg.springframework.data.redis.connection.SortParameters;
importorg.springframework.data.redis.connection.RedisZSetCommands.Tuple;
importorg.springframework.data.redis.core.ZSetOperations.TypedTuple;
importorg.springframework.data.redis.core.query.QueryUtils;
importorg.springframework.data.redis.core.query.SortQuery;
importorg.springframework.data.redis.core.script.DefaultScriptExecutor;
importorg.springframework.data.redis.core.script.RedisScript;
importorg.springframework.data.redis.core.script.ScriptExecutor;
importorg.springframework.data.redis.core.types.RedisClientInfo;
importorg.springframework.data.redis.hash.HashMapper;
importorg.springframework.data.redis.hash.ObjectHashMapper;
importorg.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
importorg.springframework.data.redis.serializer.RedisSerializer;
importorg.springframework.data.redis.serializer.SerializationUtils;
importorg.springframework.lang.Nullable;
importorg.springframework.transaction.support.TransactionSynchronizationManager;
importorg.springframework.util.Assert;
importorg.springframework.util.ClassUtils;
importorg.springframework.util.CollectionUtils;
publicclassRedisTemplate<K, V>extendsRedisAccessorimplementsRedisOperations<K, V>, BeanClassLoaderAware {
privatebooleanenableTransactionSupport=false;
privatebooleanexposeConnection=false;
privatebooleaninitialized=false;
privatebooleanenableDefaultSerializer=true;
@NullableprivateRedisSerializer<?>defaultSerializer;
@NullableprivateClassLoaderclassLoader;
@NullableprivateRedisSerializerkeySerializer=null;
@NullableprivateRedisSerializervalueSerializer=null;
@NullableprivateRedisSerializerhashKeySerializer=null;
@NullableprivateRedisSerializerhashValueSerializer=null;
privateRedisSerializer<String>stringSerializer=RedisSerializer.string();
@NullableprivateScriptExecutor<K>scriptExecutor;
privatefinalValueOperations<K, V>valueOps=newDefaultValueOperations(this);
privatefinalListOperations<K, V>listOps=newDefaultListOperations(this);
privatefinalSetOperations<K, V>setOps=newDefaultSetOperations(this);
privatefinalStreamOperations<K, ?, ?>streamOps=newDefaultStreamOperations(this, newObjectHashMapper());
privatefinalZSetOperations<K, V>zSetOps=newDefaultZSetOperations(this);
privatefinalGeoOperations<K, V>geoOps=newDefaultGeoOperations(this);
privatefinalHyperLogLogOperations<K, V>hllOps=newDefaultHyperLogLogOperations(this);
privatefinalClusterOperations<K, V>clusterOps=newDefaultClusterOperations(this);
publicRedisTemplate() {
    }
publicvoidafterPropertiesSet() {
super.afterPropertiesSet();
booleandefaultUsed=false;
if (this.defaultSerializer==null) {
this.defaultSerializer=newJdkSerializationRedisSerializer(this.classLoader!=null?this.classLoader : this.getClass().getClassLoader());
        }
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");
        }
if (this.scriptExecutor==null) {
this.scriptExecutor=newDefaultScriptExecutor(this);
        }
this.initialized=true;
    }
@Nullablepublic<T>Texecute(RedisCallback<T>action) {
returnthis.execute(action, this.isExposeConnection());
    }
@Nullablepublic<T>Texecute(RedisCallback<T>action, booleanexposeConnection) {
returnthis.execute(action, exposeConnection, false);
    }
@Nullablepublic<T>Texecute(RedisCallback<T>action, booleanexposeConnection, booleanpipeline) {
Assert.isTrue(this.initialized, "template not initialized; call afterPropertiesSet() before using it");
Assert.notNull(action, "Callback object must not be null");
RedisConnectionFactoryfactory=this.getRequiredConnectionFactory();
RedisConnectionconn=null;
Objectvar11;
try {
if (this.enableTransactionSupport) {
conn=RedisConnectionUtils.bindConnection(factory, this.enableTransactionSupport);
            } else {
conn=RedisConnectionUtils.getConnection(factory);
            }
booleanexistingConnection=TransactionSynchronizationManager.hasResource(factory);
RedisConnectionconnToUse=this.preProcessConnection(conn, existingConnection);
booleanpipelineStatus=connToUse.isPipelined();
if (pipeline&&!pipelineStatus) {
connToUse.openPipeline();
            }
RedisConnectionconnToExpose=exposeConnection?connToUse : this.createRedisConnectionProxy(connToUse);
Tresult=action.doInRedis(connToExpose);
if (pipeline&&!pipelineStatus) {
connToUse.closePipeline();
            }
var11=this.postProcessResult(result, connToUse, existingConnection);
        } finally {
RedisConnectionUtils.releaseConnection(conn, factory, this.enableTransactionSupport);
        }
returnvar11;
    }
public<T>Texecute(SessionCallback<T>session) {
Assert.isTrue(this.initialized, "template not initialized; call afterPropertiesSet() before using it");
Assert.notNull(session, "Callback object must not be null");
RedisConnectionFactoryfactory=this.getRequiredConnectionFactory();
RedisConnectionUtils.bindConnection(factory, this.enableTransactionSupport);
Objectvar3;
try {
var3=session.execute(this);
        } finally {
RedisConnectionUtils.unbindConnection(factory);
        }
returnvar3;
    }
publicList<Object>executePipelined(SessionCallback<?>session) {
returnthis.executePipelined(session, this.valueSerializer);
    }
publicList<Object>executePipelined(SessionCallback<?>session, @NullableRedisSerializer<?>resultSerializer) {
Assert.isTrue(this.initialized, "template not initialized; call afterPropertiesSet() before using it");
Assert.notNull(session, "Callback object must not be null");
RedisConnectionFactoryfactory=this.getRequiredConnectionFactory();
RedisConnectionUtils.bindConnection(factory, this.enableTransactionSupport);
Listvar4;
try {
var4= (List)this.execute((connection) -> {
connection.openPipeline();
booleanpipelinedClosed=false;
Listvar7;
try {
Objectresult=this.executeSession(session);
if (result!=null) {
thrownewInvalidDataAccessApiUsageException("Callback cannot return a non-null value as it gets overwritten by the pipeline");
                    }
List<Object>closePipeline=connection.closePipeline();
pipelinedClosed=true;
var7=this.deserializeMixedResults(closePipeline, resultSerializer, this.hashKeySerializer, this.hashValueSerializer);
                } finally {
if (!pipelinedClosed) {
connection.closePipeline();
                    }
                }
returnvar7;
            });
        } finally {
RedisConnectionUtils.unbindConnection(factory);
        }
returnvar4;
    }
publicList<Object>executePipelined(RedisCallback<?>action) {
returnthis.executePipelined(action, this.valueSerializer);
    }
publicList<Object>executePipelined(RedisCallback<?>action, @NullableRedisSerializer<?>resultSerializer) {
return (List)this.execute((connection) -> {
connection.openPipeline();
booleanpipelinedClosed=false;
Listvar7;
try {
Objectresult=action.doInRedis(connection);
if (result!=null) {
thrownewInvalidDataAccessApiUsageException("Callback cannot return a non-null value as it gets overwritten by the pipeline");
                }
List<Object>closePipeline=connection.closePipeline();
pipelinedClosed=true;
var7=this.deserializeMixedResults(closePipeline, resultSerializer, this.hashKeySerializer, this.hashValueSerializer);
            } finally {
if (!pipelinedClosed) {
connection.closePipeline();
                }
            }
returnvar7;
        });
    }
public<T>Texecute(RedisScript<T>script, List<K>keys, Object... args) {
returnthis.scriptExecutor.execute(script, keys, args);
    }
public<T>Texecute(RedisScript<T>script, RedisSerializer<?>argsSerializer, RedisSerializer<T>resultSerializer, List<K>keys, Object... args) {
returnthis.scriptExecutor.execute(script, argsSerializer, resultSerializer, keys, args);
    }
public<TextendsCloseable>TexecuteWithStickyConnection(RedisCallback<T>callback) {
Assert.isTrue(this.initialized, "template not initialized; call afterPropertiesSet() before using it");
Assert.notNull(callback, "Callback object must not be null");
RedisConnectionFactoryfactory=this.getRequiredConnectionFactory();
RedisConnectionconnection=this.preProcessConnection(RedisConnectionUtils.doGetConnection(factory, true, false, false), false);
return (Closeable)callback.doInRedis(connection);
    }
privateObjectexecuteSession(SessionCallback<?>session) {
returnsession.execute(this);
    }
protectedRedisConnectioncreateRedisConnectionProxy(RedisConnectionpm) {
Class<?>[] ifcs=ClassUtils.getAllInterfacesForClass(pm.getClass(), this.getClass().getClassLoader());
return (RedisConnection)Proxy.newProxyInstance(pm.getClass().getClassLoader(), ifcs, newCloseSuppressingInvocationHandler(pm));
    }
protectedRedisConnectionpreProcessConnection(RedisConnectionconnection, booleanexistingConnection) {
returnconnection;
    }
@Nullableprotected<T>TpostProcessResult(@NullableTresult, RedisConnectionconn, booleanexistingConnection) {
returnresult;
    }
publicbooleanisExposeConnection() {
returnthis.exposeConnection;
    }
publicvoidsetExposeConnection(booleanexposeConnection) {
this.exposeConnection=exposeConnection;
    }
publicbooleanisEnableDefaultSerializer() {
returnthis.enableDefaultSerializer;
    }
publicvoidsetEnableDefaultSerializer(booleanenableDefaultSerializer) {
this.enableDefaultSerializer=enableDefaultSerializer;
    }
@NullablepublicRedisSerializer<?>getDefaultSerializer() {
returnthis.defaultSerializer;
    }
publicvoidsetDefaultSerializer(RedisSerializer<?>serializer) {
this.defaultSerializer=serializer;
    }
publicvoidsetKeySerializer(RedisSerializer<?>serializer) {
this.keySerializer=serializer;
    }
publicRedisSerializer<?>getKeySerializer() {
returnthis.keySerializer;
    }
publicvoidsetValueSerializer(RedisSerializer<?>serializer) {
this.valueSerializer=serializer;
    }
publicRedisSerializer<?>getValueSerializer() {
returnthis.valueSerializer;
    }
publicRedisSerializer<?>getHashKeySerializer() {
returnthis.hashKeySerializer;
    }
publicvoidsetHashKeySerializer(RedisSerializer<?>hashKeySerializer) {
this.hashKeySerializer=hashKeySerializer;
    }
publicRedisSerializer<?>getHashValueSerializer() {
returnthis.hashValueSerializer;
    }
publicvoidsetHashValueSerializer(RedisSerializer<?>hashValueSerializer) {
this.hashValueSerializer=hashValueSerializer;
    }
publicRedisSerializer<String>getStringSerializer() {
returnthis.stringSerializer;
    }
publicvoidsetStringSerializer(RedisSerializer<String>stringSerializer) {
this.stringSerializer=stringSerializer;
    }
publicvoidsetScriptExecutor(ScriptExecutor<K>scriptExecutor) {
this.scriptExecutor=scriptExecutor;
    }
privatebyte[] rawKey(Objectkey) {
Assert.notNull(key, "non null key required");
returnthis.keySerializer==null&&keyinstanceofbyte[] ? (byte[])((byte[])key) : this.keySerializer.serialize(key);
    }
privatebyte[] rawString(Stringkey) {
returnthis.stringSerializer.serialize(key);
    }
privatebyte[] rawValue(Objectvalue) {
returnthis.valueSerializer==null&&valueinstanceofbyte[] ? (byte[])((byte[])value) : this.valueSerializer.serialize(value);
    }
privatebyte[][] rawKeys(Collection<K>keys) {
byte[][] rawKeys=newbyte[keys.size()][];
inti=0;
Objectkey;
for(Iteratorvar4=keys.iterator(); var4.hasNext(); rawKeys[i++] =this.rawKey(key)) {
key=var4.next();
        }
returnrawKeys;
    }
privateKdeserializeKey(byte[] value) {
returnthis.keySerializer!=null?this.keySerializer.deserialize(value) : value;
    }
@NullableprivateList<Object>deserializeMixedResults(@NullableList<Object>rawValues, @NullableRedisSerializervalueSerializer, @NullableRedisSerializerhashKeySerializer, @NullableRedisSerializerhashValueSerializer) {
if (rawValues==null) {
returnnull;
        } else {
List<Object>values=newArrayList();
Iteratorvar6=rawValues.iterator();
while(true) {
while(var6.hasNext()) {
ObjectrawValue=var6.next();
if (rawValueinstanceofbyte[] &&valueSerializer!=null) {
values.add(valueSerializer.deserialize((byte[])((byte[])rawValue)));
                    } elseif (rawValueinstanceofList) {
values.add(this.deserializeMixedResults((List)rawValue, valueSerializer, hashKeySerializer, hashValueSerializer));
                    } elseif (rawValueinstanceofSet&&!((Set)rawValue).isEmpty()) {
values.add(this.deserializeSet((Set)rawValue, valueSerializer));
                    } elseif (rawValueinstanceofMap&&!((Map)rawValue).isEmpty() && ((Map)rawValue).values().iterator().next() instanceofbyte[]) {
values.add(SerializationUtils.deserialize((Map)rawValue, hashKeySerializer, hashValueSerializer));
                    } else {
values.add(rawValue);
                    }
                }
returnvalues;
            }
        }
    }
privateSet<?>deserializeSet(SetrawSet, @NullableRedisSerializervalueSerializer) {
if (rawSet.isEmpty()) {
returnrawSet;
        } else {
ObjectsetValue=rawSet.iterator().next();
if (setValueinstanceofbyte[] &&valueSerializer!=null) {
returnSerializationUtils.deserialize(rawSet, valueSerializer);
            } else {
returnsetValueinstanceofTuple?this.convertTupleValues(rawSet, valueSerializer) : rawSet;
            }
        }
    }
privateSet<TypedTuple<V>>convertTupleValues(Set<Tuple>rawValues, @NullableRedisSerializervalueSerializer) {
Set<TypedTuple<V>>set=newLinkedHashSet(rawValues.size());
TuplerawValue;
Objectvalue;
for(Iteratorvar4=rawValues.iterator(); var4.hasNext(); set.add(newDefaultTypedTuple(value, rawValue.getScore()))) {
rawValue= (Tuple)var4.next();
value=rawValue.getValue();
if (valueSerializer!=null) {
value=valueSerializer.deserialize(rawValue.getValue());
            }
        }
returnset;
    }
publicList<Object>exec() {
List<Object>results=this.execRaw();
returnthis.getRequiredConnectionFactory().getConvertPipelineAndTxResults() ?this.deserializeMixedResults(results, this.valueSerializer, this.hashKeySerializer, this.hashValueSerializer) : results;
    }
publicList<Object>exec(RedisSerializer<?>valueSerializer) {
returnthis.deserializeMixedResults(this.execRaw(), valueSerializer, valueSerializer, valueSerializer);
    }
protectedList<Object>execRaw() {
List<Object>raw= (List)this.execute(RedisTxCommands::exec);
returnraw==null?Collections.emptyList() : raw;
    }
publicBooleandelete(Kkey) {
byte[] rawKey=this.rawKey(key);
Longresult= (Long)this.execute((connection) -> {
returnconnection.del(newbyte[][]{rawKey});
        }, true);
returnresult!=null&&result.intValue() ==1;
    }
publicLongdelete(Collection<K>keys) {
if (CollectionUtils.isEmpty(keys)) {
return0L;
        } else {
byte[][] rawKeys=this.rawKeys(keys);
return (Long)this.execute((connection) -> {
returnconnection.del(rawKeys);
            }, true);
        }
    }
publicBooleanunlink(Kkey) {
byte[] rawKey=this.rawKey(key);
Longresult= (Long)this.execute((connection) -> {
returnconnection.unlink(newbyte[][]{rawKey});
        }, true);
returnresult!=null&&result.intValue() ==1;
    }
publicLongunlink(Collection<K>keys) {
if (CollectionUtils.isEmpty(keys)) {
return0L;
        } else {
byte[][] rawKeys=this.rawKeys(keys);
return (Long)this.execute((connection) -> {
returnconnection.unlink(rawKeys);
            }, true);
        }
    }
publicBooleanhasKey(Kkey) {
byte[] rawKey=this.rawKey(key);
return (Boolean)this.execute((connection) -> {
returnconnection.exists(rawKey);
        }, true);
    }
publicLongcountExistingKeys(Collection<K>keys) {
Assert.notNull(keys, "Keys must not be null!");
byte[][] rawKeys=this.rawKeys(keys);
return (Long)this.execute((connection) -> {
returnconnection.exists(rawKeys);
        }, true);
    }
publicBooleanexpire(Kkey, longtimeout, TimeUnitunit) {
byte[] rawKey=this.rawKey(key);
longrawTimeout=TimeoutUtils.toMillis(timeout, unit);
return (Boolean)this.execute((connection) -> {
try {
returnconnection.pExpire(rawKey, rawTimeout);
            } catch (Exceptionvar8) {
returnconnection.expire(rawKey, TimeoutUtils.toSeconds(timeout, unit));
            }
        }, true);
    }
publicBooleanexpireAt(Kkey, Datedate) {
byte[] rawKey=this.rawKey(key);
return (Boolean)this.execute((connection) -> {
try {
returnconnection.pExpireAt(rawKey, date.getTime());
            } catch (Exceptionvar4) {
returnconnection.expireAt(rawKey, date.getTime() /1000L);
            }
        }, true);
    }
publicvoidconvertAndSend(Stringchannel, Objectmessage) {
Assert.hasText(channel, "a non-empty channel is required");
byte[] rawChannel=this.rawString(channel);
byte[] rawMessage=this.rawValue(message);
this.execute((connection) -> {
connection.publish(rawChannel, rawMessage);
returnnull;
        }, true);
    }
publicLonggetExpire(Kkey) {
byte[] rawKey=this.rawKey(key);
return (Long)this.execute((connection) -> {
returnconnection.ttl(rawKey);
        }, true);
    }
publicLonggetExpire(Kkey, TimeUnittimeUnit) {
byte[] rawKey=this.rawKey(key);
return (Long)this.execute((connection) -> {
try {
returnconnection.pTtl(rawKey, timeUnit);
            } catch (Exceptionvar4) {
returnconnection.ttl(rawKey, timeUnit);
            }
        }, true);
    }
publicSet<K>keys(Kpattern) {
byte[] rawKey=this.rawKey(pattern);
Set<byte[]>rawKeys= (Set)this.execute((connection) -> {
returnconnection.keys(rawKey);
        }, true);
returnthis.keySerializer!=null?SerializationUtils.deserialize(rawKeys, this.keySerializer) : rawKeys;
    }
publicBooleanpersist(Kkey) {
byte[] rawKey=this.rawKey(key);
return (Boolean)this.execute((connection) -> {
returnconnection.persist(rawKey);
        }, true);
    }
publicBooleanmove(Kkey, intdbIndex) {
byte[] rawKey=this.rawKey(key);
return (Boolean)this.execute((connection) -> {
returnconnection.move(rawKey, dbIndex);
        }, true);
    }
publicKrandomKey() {
byte[] rawKey= (byte[])this.execute(RedisKeyCommands::randomKey, true);
returnthis.deserializeKey(rawKey);
    }
publicvoidrename(KoldKey, KnewKey) {
byte[] rawOldKey=this.rawKey(oldKey);
byte[] rawNewKey=this.rawKey(newKey);
this.execute((connection) -> {
connection.rename(rawOldKey, rawNewKey);
returnnull;
        }, true);
    }
publicBooleanrenameIfAbsent(KoldKey, KnewKey) {
byte[] rawOldKey=this.rawKey(oldKey);
byte[] rawNewKey=this.rawKey(newKey);
return (Boolean)this.execute((connection) -> {
returnconnection.renameNX(rawOldKey, rawNewKey);
        }, true);
    }
publicDataTypetype(Kkey) {
byte[] rawKey=this.rawKey(key);
return (DataType)this.execute((connection) -> {
returnconnection.type(rawKey);
        }, true);
    }
publicbyte[] dump(Kkey) {
byte[] rawKey=this.rawKey(key);
return (byte[])this.execute((connection) -> {
returnconnection.dump(rawKey);
        }, true);
    }
publicvoidrestore(Kkey, byte[] value, longtimeToLive, TimeUnitunit, booleanreplace) {
byte[] rawKey=this.rawKey(key);
longrawTimeout=TimeoutUtils.toMillis(timeToLive, unit);
this.execute((connection) -> {
connection.restore(rawKey, rawTimeout, value, replace);
returnnull;
        }, true);
    }
publicvoidmulti() {
this.execute((connection) -> {
connection.multi();
returnnull;
        }, true);
    }
publicvoiddiscard() {
this.execute((connection) -> {
connection.discard();
returnnull;
        }, true);
    }
publicvoidwatch(Kkey) {
byte[] rawKey=this.rawKey(key);
this.execute((connection) -> {
connection.watch(newbyte[][]{rawKey});
returnnull;
        }, true);
    }
publicvoidwatch(Collection<K>keys) {
byte[][] rawKeys=this.rawKeys(keys);
this.execute((connection) -> {
connection.watch(rawKeys);
returnnull;
        }, true);
    }
publicvoidunwatch() {
this.execute((connection) -> {
connection.unwatch();
returnnull;
        }, true);
    }
publicList<V>sort(SortQuery<K>query) {
returnthis.sort(query, this.valueSerializer);
    }
public<T>List<T>sort(SortQuery<K>query, @NullableRedisSerializer<T>resultSerializer) {
byte[] rawKey=this.rawKey(query.getKey());
SortParametersparams=QueryUtils.convertQuery(query, this.stringSerializer);
List<byte[]>vals= (List)this.execute((connection) -> {
returnconnection.sort(rawKey, params);
        }, true);
returnSerializationUtils.deserialize(vals, resultSerializer);
    }
public<T>List<T>sort(SortQuery<K>query, BulkMapper<T, V>bulkMapper) {
returnthis.sort(query, bulkMapper, this.valueSerializer);
    }
public<T, S>List<T>sort(SortQuery<K>query, BulkMapper<T, S>bulkMapper, @NullableRedisSerializer<S>resultSerializer) {
List<S>values=this.sort(query, resultSerializer);
if (values!=null&&!values.isEmpty()) {
intbulkSize=query.getGetPattern().size();
List<T>result=newArrayList(values.size() /bulkSize+1);
List<S>bulk=newArrayList(bulkSize);
Iteratorvar8=values.iterator();
while(var8.hasNext()) {
Ss=var8.next();
bulk.add(s);
if (bulk.size() ==bulkSize) {
result.add(bulkMapper.mapBulk(Collections.unmodifiableList(bulk)));
bulk=newArrayList(bulkSize);
                }
            }
returnresult;
        } else {
returnCollections.emptyList();
        }
    }
publicLongsort(SortQuery<K>query, KstoreKey) {
byte[] rawStoreKey=this.rawKey(storeKey);
byte[] rawKey=this.rawKey(query.getKey());
SortParametersparams=QueryUtils.convertQuery(query, this.stringSerializer);
return (Long)this.execute((connection) -> {
returnconnection.sort(rawKey, params, rawStoreKey);
        }, true);
    }
publicvoidkillClient(Stringhost, intport) {
this.execute((connection) -> {
connection.killClient(host, port);
returnnull;
        });
    }
publicList<RedisClientInfo>getClientList() {
return (List)this.execute(RedisServerCommands::getClientList);
    }
publicvoidslaveOf(Stringhost, intport) {
this.execute((connection) -> {
connection.slaveOf(host, port);
returnnull;
        });
    }
publicvoidslaveOfNoOne() {
this.execute((connection) -> {
connection.slaveOfNoOne();
returnnull;
        });
    }
publicClusterOperations<K, V>opsForCluster() {
returnthis.clusterOps;
    }
publicGeoOperations<K, V>opsForGeo() {
returnthis.geoOps;
    }
publicBoundGeoOperations<K, V>boundGeoOps(Kkey) {
returnnewDefaultBoundGeoOperations(key, this);
    }
public<HK, HV>BoundHashOperations<K, HK, HV>boundHashOps(Kkey) {
returnnewDefaultBoundHashOperations(key, this);
    }
public<HK, HV>HashOperations<K, HK, HV>opsForHash() {
returnnewDefaultHashOperations(this);
    }
publicHyperLogLogOperations<K, V>opsForHyperLogLog() {
returnthis.hllOps;
    }
publicListOperations<K, V>opsForList() {
returnthis.listOps;
    }
publicBoundListOperations<K, V>boundListOps(Kkey) {
returnnewDefaultBoundListOperations(key, this);
    }
publicBoundSetOperations<K, V>boundSetOps(Kkey) {
returnnewDefaultBoundSetOperations(key, this);
    }
publicSetOperations<K, V>opsForSet() {
returnthis.setOps;
    }
public<HK, HV>StreamOperations<K, HK, HV>opsForStream() {
returnthis.streamOps;
    }
public<HK, HV>StreamOperations<K, HK, HV>opsForStream(HashMapper<?superK, ?superHK, ?superHV>hashMapper) {
returnnewDefaultStreamOperations(this, hashMapper);
    }
public<HK, HV>BoundStreamOperations<K, HK, HV>boundStreamOps(Kkey) {
returnnewDefaultBoundStreamOperations(key, this);
    }
publicBoundValueOperations<K, V>boundValueOps(Kkey) {
returnnewDefaultBoundValueOperations(key, this);
    }
publicValueOperations<K, V>opsForValue() {
returnthis.valueOps;
    }
publicBoundZSetOperations<K, V>boundZSetOps(Kkey) {
returnnewDefaultBoundZSetOperations(key, this);
    }
publicZSetOperations<K, V>opsForZSet() {
returnthis.zSetOps;
    }
publicvoidsetEnableTransactionSupport(booleanenableTransactionSupport) {
this.enableTransactionSupport=enableTransactionSupport;
    }
publicvoidsetBeanClassLoader(ClassLoaderclassLoader) {
this.classLoader=classLoader;
    }
}


有兴趣可以看看以上类中都有啥功能。


写一个简单的工具类:

packagecom.xing.study.util;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.data.redis.core.*;
importorg.springframework.stereotype.Service;
importjava.util.List;
importjava.util.Set;
importjava.util.concurrent.TimeUnit;
@ServicepublicclassRedisUtils {
privatefinalRedisTemplate<String, Object>redisTemplate;
@AutowiredpublicRedisUtils(RedisTemplateredisTemplate){
this.redisTemplate=redisTemplate;
    }
/*** 写入缓存* @param key 键* @param value 值* @return 结果*/publicbooleanset(finalStringkey, Objectvalue) {
booleanresult=false;
try {
ValueOperations<String, Object>operations=redisTemplate.opsForValue();
operations.set(key, value);
result=true;
        } catch (Exceptione) {
e.printStackTrace();
        }
returnresult;
    }
/*** 写入缓存设置时效时间* @param key 键* @param value 值* @return 结果*/publicbooleanset(finalStringkey, Objectvalue, LongexpireTime , TimeUnittimeUnit) {
booleanresult=false;
try {
ValueOperations<String, Object>operations=redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result=true;
        } catch (Exceptione) {
e.printStackTrace();
        }
returnresult;
    }
/*** 批量删除对应的value* @param keys 键 key1,key2...*/publicvoidremove(finalString... keys) {
for (Stringkey : keys) {
remove(key);
        }
    }
/*** 批量删除key* @param pattern 匹配符*/publicvoidremovePattern(finalStringpattern) {
Set<String>keys=redisTemplate.keys(pattern);
if (keys!=null&&keys.size() >0){
redisTemplate.delete(keys);
        }
    }
/*** 删除对应的value* @param key 键*/publicvoidremove(finalStringkey) {
if (exists(key)) {
redisTemplate.delete(key);
        }
    }
/*** 判断缓存中是否有对应的value* @param key 键* @return 存在则true*/publicbooleanexists(finalStringkey) {
returnredisTemplate.hasKey(key);
    }
/*** 读取缓存* @param key 键* @return 值*/publicObjectget(finalStringkey) {
Objectresult=null;
ValueOperations<String, Object>operations=redisTemplate.opsForValue();
result=operations.get(key);
returnresult;
    }
/*** 哈希 添加* @param key 键* @param hashKey hash* @param value 值*/publicvoidhmSet(Stringkey, ObjecthashKey, Objectvalue){
HashOperations<String, Object, Object>hash=redisTemplate.opsForHash();
hash.put(key,hashKey,value);
    }
/*** 哈希获取数据* @param key 键* @param hashKey hash* @return 值*/publicObjecthmGet(Stringkey, ObjecthashKey){
HashOperations<String, Object, Object>hash=redisTemplate.opsForHash();
returnhash.get(key,hashKey);
    }
/*** 列表添加* @param k 键* @param v 值*/publicvoidlPush(Stringk,Objectv){
ListOperations<String, Object>list=redisTemplate.opsForList();
list.rightPush(k,v);
    }
/*** 列表获取* @param k 键* @param l l* @param l1 l1* @return 值*/publicList<Object>lRange(Stringk, longl, longl1){
ListOperations<String, Object>list=redisTemplate.opsForList();
returnlist.range(k,l,l1);
    }
/*** 集合添加* @param key 键* @param value 值*/publicvoidadd(Stringkey,Objectvalue){
SetOperations<String, Object>set=redisTemplate.opsForSet();
set.add(key,value);
    }
/*** 集合获取* @param key 键* @return 值*/publicSet<Object>setMembers(Stringkey){
SetOperations<String, Object>set=redisTemplate.opsForSet();
returnset.members(key);
    }
/*** 有序集合添加* @param key 键* @param value 值* @param score 排序*/publicvoidzAdd(Stringkey,Objectvalue,doublescore){
ZSetOperations<String, Object>zset=redisTemplate.opsForZSet();
zset.add(key,value,score);
    }
/*** 有序集合获取* @param key 键* @param scoure 区间开始* @param scoure1 区间结束* @return 值*/publicSet<Object>rangeByScore(Stringkey,doublescoure,doublescoure1){
ZSetOperations<String, Object>zset=redisTemplate.opsForZSet();
returnzset.rangeByScore(key, scoure, scoure1);
    }
}
在controller中测试一下:packagecom.xing.study.controller;
importcom.xing.study.util.RedisUtils;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
importjava.util.concurrent.TimeUnit;
@RestControllerpublicclassDemoController {
privatefinalRedisUtilsredisUtils;
@AutowiredpublicDemoController(RedisUtilsredisUtils){
this.redisUtils=redisUtils;
    }
@RequestMapping("/hello/{id}")
publicStringfirst(@PathVariable("id")Stringid){
//查询缓存中是否存在booleanhasKey=redisUtils.exists(id);
Stringstr="";
if(hasKey){
//获取缓存Objectobject=redisUtils.get(id);
System.out.println("从缓存获取的数据"+object);
str=object.toString();
        }else{
//从数据库中获取信息System.out.println("从数据库中获取数据");
str="哦吼吼";
//数据插入缓存(set中的参数含义:key值,user对象,缓存存在时间10(long类型),时间单位)redisUtils.set(id,str,10L, TimeUnit.MINUTES);
System.out.println("数据插入缓存"+str);
        }
returnstr;
    }
@RequestMapping("/delete/{id}")
publicStringdelete(@PathVariable("id") Stringid){
redisUtils.remove(id);
System.out.println("从缓存中删除数据");
return"delete success->"+id;
    }
@RequestMapping("/common/{type}/{key}/{value}")
publicStringcommon(@PathVariable("type") Stringtype,@PathVariable("key") Stringkey,@PathVariable("value") Stringvalue){
switch (type) {
case"addStr":
redisUtils.set(key,value);
break;
case"deletes":
redisUtils.remove("123");
break;
default:
System.out.println("默认。。。");
        }
return"success";
    }
}


浏览器访问:http://127.0.0.1:8889/hello/123

image.png


控制台发现是从缓存中取得,打开数据库也可以看到已存储。

image.png



总结:

       使用RedisTemplate各种API来操作数据库。


END

相关实践学习
基于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
目录
相关文章
|
2月前
|
缓存 NoSQL Java
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解分布式情况下如何添加分布式锁 【续篇】
这篇文章是关于如何在SpringBoot应用中整合Redis并处理分布式场景下的缓存问题,包括缓存穿透、缓存雪崩和缓存击穿。文章详细讨论了在分布式情况下如何添加分布式锁来解决缓存击穿问题,提供了加锁和解锁的实现过程,并展示了使用JMeter进行压力测试来验证锁机制有效性的方法。
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解分布式情况下如何添加分布式锁 【续篇】
|
2月前
|
编解码 NoSQL Java
使用Spring Boot + Redis 队列实现视频文件上传及FFmpeg转码的技术分享
【8月更文挑战第30天】在当前的互联网应用中,视频内容的处理与分发已成为不可或缺的一部分。对于视频平台而言,高效、稳定地处理用户上传的视频文件,并对其进行转码以适应不同设备的播放需求,是提升用户体验的关键。本文将围绕使用Spring Boot结合Redis队列技术来实现视频文件上传及FFmpeg转码的过程,分享一系列技术干货。
87 3
|
6天前
|
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序列化)
|
2月前
|
缓存 NoSQL Java
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解、如何添加锁解决缓存击穿问题?分布式情况下如何添加分布式锁
这篇文章介绍了如何在SpringBoot项目中整合Redis,并探讨了缓存穿透、缓存雪崩和缓存击穿的问题以及解决方法。文章还提供了解决缓存击穿问题的加锁示例代码,包括存在问题和问题解决后的版本,并指出了本地锁在分布式情况下的局限性,引出了分布式锁的概念。
SpringBoot整合Redis、以及缓存穿透、缓存雪崩、缓存击穿的理解、如何添加锁解决缓存击穿问题?分布式情况下如何添加分布式锁
|
2月前
|
NoSQL Java Redis
Redis6入门到实战------ 八、Redis与Spring Boot整合
这篇文章详细介绍了如何在Spring Boot项目中整合Redis,包括在`pom.xml`中添加依赖、配置`application.properties`文件、创建配置类以及编写测试类来验证Redis的连接和基本操作。
Redis6入门到实战------ 八、Redis与Spring Boot整合
|
2月前
|
NoSQL Java Redis
springboot整合redis
这篇文章介绍了如何在Spring Boot中整合Redis,包括搭建Redis环境、添加依赖、创建实体类、控制器以及配置文件,并说明了在连接Redis时需要启动Redis服务。
springboot整合redis
|
2月前
|
Web App开发 前端开发 关系型数据库
基于SpringBoot+Vue+Redis+Mybatis的商城购物系统 【系统实现+系统源码+答辩PPT】
这篇文章介绍了一个基于SpringBoot+Vue+Redis+Mybatis技术栈开发的商城购物系统,包括系统功能、页面展示、前后端项目结构和核心代码,以及如何获取系统源码和答辩PPT的方法。
|
2月前
|
NoSQL Java Linux
springboot+redis+虚拟机 springboot连接linux虚拟机中的redis服务
该博客文章介绍了如何在Spring Boot项目中通过配置和代码实现连接运行在Linux虚拟机上的Redis服务,并提供了详细的步骤和测试结果截图。
springboot+redis+虚拟机 springboot连接linux虚拟机中的redis服务
|
2月前
|
缓存 NoSQL Java
惊!Spring Boot遇上Redis,竟开启了一场缓存实战的革命!
【8月更文挑战第29天】在互联网时代,数据的高速读写至关重要。Spring Boot凭借简洁高效的特点广受开发者喜爱,而Redis作为高性能内存数据库,在缓存和消息队列领域表现出色。本文通过电商平台商品推荐系统的实战案例,详细介绍如何在Spring Boot项目中整合Redis,提升系统响应速度和用户体验。
52 0
|
2月前
|
缓存 NoSQL Java
【Azure Redis 缓存】定位Java Spring Boot 使用 Jedis 或 Lettuce 无法连接到 Redis的网络连通性步骤
【Azure Redis 缓存】定位Java Spring Boot 使用 Jedis 或 Lettuce 无法连接到 Redis的网络连通性步骤
下一篇
无影云桌面