springboot 2.x整合redis

引入redis依賴

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

設(shè)置連接redis的配置

Redis配置

spring.redis.port=6379
spring.redis.host=your host
spring.redis.password=your password

配置redis連接

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 使用Jackson2JsonRedisSerialize 替換默認(rèn)的jdkSerializeable序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 設(shè)置value的序列化規(guī)則和 key的序列化規(guī)則
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

開(kāi)始使用

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRedisApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void contextLoads() {

        redisTemplate.opsForValue().set("name","hansn");
        String s = (String) redisTemplate.opsForValue().get("name");
        System.out.println(s);

        //設(shè)置過(guò)期時(shí)間
        redisTemplate.opsForValue().set("name1","hansn007",10,TimeUnit.MINUTES);
        String s1 = (String) redisTemplate.opsForValue().get("name1");
        System.out.println(s1);
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 超強(qiáng)、超詳細(xì)Redis入門(mén)教程 轉(zhuǎn)載2017年03月04日 16:20:02 16916 轉(zhuǎn)載自: http://...
    邵云濤閱讀 17,633評(píng)論 3 313
  • 文章已經(jīng)放到github上 ,如果對(duì)您有幫助 請(qǐng)給個(gè)star[https://github.com/qqxuanl...
    尼爾君閱讀 2,346評(píng)論 0 22
  • 【本教程目錄】 1.redis是什么2.redis的作者3.誰(shuí)在使用redis4.學(xué)會(huì)安裝redis5.學(xué)會(huì)啟動(dòng)r...
    徐猿猿閱讀 1,921評(píng)論 0 35
  • 來(lái)源:腳本之家 這篇文章主要介紹了超強(qiáng)、超詳細(xì)Redis入門(mén)教程,本文詳細(xì)介紹了Redis數(shù)據(jù)庫(kù)各個(gè)方面的知識(shí),需...
    shenyoujian閱讀 922評(píng)論 1 10
  • 2017年4月3日天氣格外的晴朗,是一個(gè)踏青、出游的好季節(jié)。今天來(lái)到了貴州遵義湄潭永興鎮(zhèn)探訪平時(shí)我們所喝的農(nóng)家茶是...
    找茬客閱讀 296評(píng)論 0 0

友情鏈接更多精彩內(nèi)容