文章出處

Springboot系列redis使用之1:在互聯網的應用中,redis被廣泛地使用。而在spring boot中使用redis,是非常簡單的。

spring boot 中的redis

要在spring boot中使用redis,在pom中加入spring-boot-starter-redis依賴。maven會添加spring-data-redis包,其中包含了jedis,jredis,lettuce,srp幾種實現。spring boot缺省選擇jedis實現使用。

jedis配置

缺省使用localhost的redis配置,如果你沒有修改任何配置,在本機上測試,不需要做任何配置。但在生成環境,必須配置真實的環境。

spring:    # REDIS (RedisProperties)    redis:        # Redis數據庫索引(默認為0)            database:0        # Redis服務器地址        host:localhost        # Redis服務器連接端口        port:6379        # Redis服務器連接密碼(默認為空)        password:        # 連接池最大連接數(使用負值表示沒有限制)        pool.max-active:8        # 連接池最大阻塞等待時間(使用負值表示沒有限制)        pool.max-wait:-1        # 連接池中的最大空閑連接        pool.max-idle:8        # 連接池中的最小空閑連接        pool.min-idle:0        # 連接超時時間(毫秒)        timeout:0

使用StringRedisTemplate來處理String

在spring-data-redis中提供了StringRedisTemplate,可以直接用來處理String數據了。

// 可以直接使用,spring會綁定 @Autowiredprivate StringRedisTemplate template;@RequestMapping("/foo")@ResponseBodypublic String foo() {        ValueOperations ops = template.opsForValue();        String key = "spring.boot.redis.test";        if (!this.template.hasKey(key)) {            String str = "not found the key, now set it";            log.info(str);            ops.set(key, str);            return str;        } else {            String str = "Found key " + key + ", value=" + ops.get(key);            log.info(str);            return str;        }    }   ,>

可以看一下spring中的實現類:

/* * Copyright 2011-2013 the original author or authors. *  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *  *      http://www.apache.org/licenses/LICENSE-2.0 *  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.springframework.data.redis.core;import org.springframework.data.redis.connection.DefaultStringRedisConnection;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.connection.StringRedisConnection;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;/** * String-focused extension of RedisTemplate. Since most operations against Redis are String based, this class provides * a dedicated class that minimizes configuration of its more generic {@link RedisTemplate template} especially in terms * of serializers. * 

* Note that this template exposes the {@link RedisConnection} used by the {@link RedisCallback} as a * {@link StringRedisConnection}. * * @author Costin Leau */ public class StringRedisTemplate extends RedisTemplate { /** * Constructs a new StringRedisTemplate instance. {@link #setConnectionFactory(RedisConnectionFactory)} * and {@link #afterPropertiesSet()} still need to be called. */ public StringRedisTemplate() { RedisSerializer stringSerializer = new StringRedisSerializer(); setKeySerializer(stringSerializer); setValueSerializer(stringSerializer); setHashKeySerializer(stringSerializer); setHashValueSerializer(stringSerializer); } /** * Constructs a new StringRedisTemplate instance ready to be used. * * @param connectionFactory connection factory for creating new connections */ public StringRedisTemplate(RedisConnectionFactory connectionFactory) { this(); setConnectionFactory(connectionFactory); afterPropertiesSet(); } protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) { return new DefaultStringRedisConnection(connection); } } ,>

在實現中,RedisTemplate和其子類中包含了幾種不同的Serializer,分別對應Key,Value,Hash……,而最簡單的String類型,在stringSerializer變量上實例化為StringRedisSerializer。

public class RedisTemplate extends RedisAccessor implements RedisOperations, 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 stringSerializer = new StringRedisSerializer(); ... /**   * Constructs a new RedisTemplate instance.   */    public RedisTemplate() {}    public void afterPropertiesSet() {        super.afterPropertiesSet();        boolean defaultUsed = false;        if (defaultSerializer == null) {            defaultSerializer = new JdkSerializationRedisSerializer(                    classLoader != null ? classLoader : this.getClass().getClassLoader());        }        if (enableDefaultSerializer) {            if (keySerializer == null) {                keySerializer = defaultSerializer;                defaultUsed = true;            }            if (valueSerializer == null) {                valueSerializer = defaultSerializer;                defaultUsed = true;            }            if (hashKeySerializer == null) {                hashKeySerializer = defaultSerializer;                defaultUsed = true;            }            if (hashValueSerializer == null) {                hashValueSerializer = defaultSerializer;                defaultUsed = true;            }        }        if (enableDefaultSerializer && defaultUsed) {            Assert.notNull(defaultSerializer, "default serializer null and not all serializers initialized");        }        if (scriptExecutor == null) {            this.scriptExecutor = new DefaultScriptExecutor(this);        }        initialized = true;    }} ,>,>

可以看到spring boot應用在啟動時,如果沒有檢查到對應的對象配置,則最后實例化defaultSerializer對象為JdkSerializationRedisSerializer了。

可以看一下運行時的對象
StringRedisTemplate對象實例

使用RedisTemplate

在程序中使用 RedisTemplate,如上所說,需要配置對應的serializer,否則對對應的數據處理時,要么serializer對象為null,要么使用的缺省的則使用JdkSerializationRedisSerializer。

要配置我們的redisTemplate對象,可以在配置類中定義一個redisTemplate 的bean。

@Bean      public RedisTemplate redisTemplate(              RedisConnectionFactory factory) {          StringRedisTemplate template = new StringRedisTemplate(factory);          Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);          ObjectMapper om = new ObjectMapper();          om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);          om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);          jackson2JsonRedisSerializer.setObjectMapper(om);          template.setValueSerializer(jackson2JsonRedisSerializer);          template.afterPropertiesSet();          return template;      } ,>

在配置類中,定義了Jackson2JsonRedisSerializer,來作為ValueSerializer對象,對Model對象進行序列化和反序列化。

然后在程序處理的地方,可以使用這個bean對象了。

@Autowiredprivate RedisTemplate redisTemplate;@RequestMapping("/user/{id}")@ResponseBodypublic String getUser(@PathVariable("id") long id) {    log.info("---- getUser");    //    User user = new User(id, "aa@126.com", "aa", "aa123456", "aa", "123");    ValueOperations operations = redisTemplate.opsForValue();    operations.set("com.dcloud.user", user);    // 有超時時間的redis set..    operations.set("com.dcloud.user.ex", user, 10, TimeUnit.SECONDS);    //    boolean exists = redisTemplate.hasKey("com.dcloud.user");    if (exists) {        log.info("exists is true");    } else {        log.info("exists is false");    }    return "finished";}@RequestMapping(value = "/query")@ResponseBodypublic String query() {    log.info("query from redis");    ValueOperations operations = redisTemplate.opsForValue();    //     User ret = operations.get("com.dcloud.user");    if (null == ret) {        log.info("not exist user");        return "finished query, and not exists";    }    log.info(ret.toString());    return "finished query";},>,>

現在可以看一下運行時的redisTemplate對象
配置的redisTemple

看文倉www.kanwencang.com網友整理上傳,為您提供最全的知識大全,期待您的分享,轉載請注明出處。
歡迎轉載:http://www.kanwencang.com/bangong/20170203/97369.html

文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()