美文网首页
RedisTemplate API使用

RedisTemplate API使用

作者: 可爱的尖椒肉丝 | 来源:发表于2019-08-24 17:31 被阅读0次

    由于之前的老的项目一直在使用 Jedis 作为Redis的Java客户端操作数据,Jedis 与JedisPool 作为官方推荐的API,其操作与redis-cli 客户端操作如出一辙,在Spring 大行其道的时代,当然也需要好好了解下RedisTemplate 的操作以及源码。

    RedisTemplate的类图如下:
    Redis的类图.jpg

    通过源码分析:
    RedisOperations --定义了Redis的基本操作,提供可扩展性,由 RedisTemplate 实现。
    RedisAccessor --定义了RedisTemplate 的一些公有属性
    InitializingBean --Spring Bean 对象的初始化,其内部仅仅有一个方法:afterPropertiesSet ,只要是实现该接口,均会在Bean对象初始化时调用该方法

    RedisAccessor 源码
    public class RedisAccessor implements InitializingBean {
    
        protected final Log logger = LogFactory.getLog(getClass());
    
        private RedisConnectionFactory connectionFactory;
    
        public void afterPropertiesSet() {
            Assert.notNull(getConnectionFactory(), "RedisConnectionFactory is required");
        }
    
        /**
         * Returns the connectionFactory.
         */
        public RedisConnectionFactory getConnectionFactory() {
            return connectionFactory;
        }
    
        /**
         * Sets the connection factory.
         */
        public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
            this.connectionFactory = connectionFactory;
        }
    
    InitializingBean 源码
    public interface InitializingBean {
    
        void afterPropertiesSet() throws Exception;
    
    }
    
    RedisTemplate 源码分析

    Helper class that simplifies Redis data access code.
    简化Redis数据访问代码的Helper类

    RedisTemplate的核心方法execute
    public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {
            Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");
            Assert.notNull(action, "Callback object must not be null");
    
            RedisConnectionFactory factory = getConnectionFactory();
            RedisConnection conn = null;
            try {
    
                if (enableTransactionSupport) {
                    // only bind resources in case of potential transaction synchronization
                    conn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);
                } else {
                    conn = RedisConnectionUtils.getConnection(factory);
                }
    
                boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);
    
                RedisConnection connToUse = preProcessConnection(conn, existingConnection);
    
                boolean pipelineStatus = connToUse.isPipelined();
                if (pipeline && !pipelineStatus) {
                    connToUse.openPipeline();
                }
    
                RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse));
                T result = action.doInRedis(connToExpose);
    
                // close pipeline
                if (pipeline && !pipelineStatus) {
                    connToUse.closePipeline();
                }
    
                // TODO: any other connection processing?
                return postProcessResult(result, connToUse, existingConnection);
            } finally {
    
                if (enableTransactionSupport) {
                    RedisConnectionUtils.unbindConnection(factory);
                } else {
                    RedisConnectionUtils.releaseConnection(conn, factory);
                }
            }
        }
    
    1. 根据RedisConnectionFactory 获取 RedisConnection
    2. 执行RedisCallback. doInRedis
    3. 返回结果
    RedisTemplate String 字符串操作
      public class StringRedisTemplate extends RedisTemplate<String, String> {
        public StringRedisTemplate() {
            RedisSerializer<String> stringSerializer = new StringRedisSerializer();
            setKeySerializer(stringSerializer);
            setValueSerializer(stringSerializer);
            setHashKeySerializer(stringSerializer);
            setHashValueSerializer(stringSerializer);
        }
    
        public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
            this();
            setConnectionFactory(connectionFactory);
            afterPropertiesSet();
        }
    
        protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
            return new DefaultStringRedisConnection(connection);
        }
    }
    

    未完,待续

    相关文章

      网友评论

          本文标题:RedisTemplate API使用

          本文链接:https://www.haomeiwen.com/subject/trltsctx.html