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; privateRedisSerializer<?>defaultSerializer; privateClassLoaderclassLoader; privateRedisSerializerkeySerializer=null; privateRedisSerializervalueSerializer=null; privateRedisSerializerhashKeySerializer=null; privateRedisSerializerhashValueSerializer=null; privateRedisSerializer<String>stringSerializer=RedisSerializer.string(); privateScriptExecutor<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; } public<T>Texecute(RedisCallback<T>action) { returnthis.execute(action, this.isExposeConnection()); } public<T>Texecute(RedisCallback<T>action, booleanexposeConnection) { returnthis.execute(action, exposeConnection, false); } public<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, RedisSerializer<?>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, RedisSerializer<?>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; } protected<T>TpostProcessResult(Tresult, RedisConnectionconn, booleanexistingConnection) { returnresult; } publicbooleanisExposeConnection() { returnthis.exposeConnection; } publicvoidsetExposeConnection(booleanexposeConnection) { this.exposeConnection=exposeConnection; } publicbooleanisEnableDefaultSerializer() { returnthis.enableDefaultSerializer; } publicvoidsetEnableDefaultSerializer(booleanenableDefaultSerializer) { this.enableDefaultSerializer=enableDefaultSerializer; } publicRedisSerializer<?>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; } privateList<Object>deserializeMixedResults(List<Object>rawValues, RedisSerializervalueSerializer, RedisSerializerhashKeySerializer, RedisSerializerhashValueSerializer) { 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, RedisSerializervalueSerializer) { 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, RedisSerializervalueSerializer) { 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, RedisSerializer<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, RedisSerializer<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; publicclassRedisUtils { privatefinalRedisTemplate<String, Object>redisTemplate; publicRedisUtils(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; publicclassDemoController { privatefinalRedisUtilsredisUtils; publicDemoController(RedisUtilsredisUtils){ this.redisUtils=redisUtils; } "/hello/{id}") (publicStringfirst( ("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; } "/delete/{id}") (publicStringdelete( ("id") Stringid){ redisUtils.remove(id); System.out.println("从缓存中删除数据"); return"delete success->"+id; } "/common/{type}/{key}/{value}") (publicStringcommon( ("type") Stringtype, ("key") Stringkey, ("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
控制台发现是从缓存中取得,打开数据库也可以看到已存储。
总结:
使用RedisTemplate各种API来操作数据库。
END