亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot集成Redis流程詳解

 更新時間:2023年05月08日 09:11:29   作者:掉頭發(fā)的王富貴  
這篇文章主要介紹了SpringBoot集成Redis流程詳解,導(dǎo)入jar包,編寫配置類,編寫util類,配置yml這四個步驟,有詳細的代碼示例,,需要的朋友可以參考下

第一步,導(dǎo)入jar包

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

第二步,編寫配置類

這是一個使用FastJson序列化器,配置RedisTemplate的Spring Bean的Java類。該類使用了@Configuration注釋來標識這是一個配置類,并使用@Bean注釋來標識該方法是創(chuàng)建一個Bean的工廠方法。該方法名為redisTemplate,并使用了@ConditionalOnMissingBean注釋,表示如果在上下文中沒有StringRedisTemplate類型的Bean,則會自動創(chuàng)建一個該類型的Bean。該方法返回一個RedisTemplate類型的對象,該對象被配置為使用FastJson序列化器,以便將對象序列化為JSON格式進行存儲和檢索。在方法內(nèi)部,通過setConnectionFactory方法設(shè)置了RedisTemplate的連接工廠,并通過setKeySerializer和setValueSerializer方法設(shè)置了鍵和值的序列化器。此外,該類還提供了一個名為stringRedisTemplate的方法,用于創(chuàng)建StringRedisTemplate類型的Bean。

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    /**
     * 重寫Redis序列化方式,使用Json方式: * 當我們的數(shù)據(jù)存儲到Redis的時候,我們的鍵(key)和值(value)
     * 都是通過Spring提供的Serializer序列化到數(shù)據(jù)庫的。RedisTemplate默認使用的是JdkSerializationRedisSerializer,
     * StringRedisTemplate默認使用的是StringRedisSerializer。
     * Spring Data JPA為我們提供了下面的Serializer:
     * GenericToStringSerializer、Jackson2JsonRedisSerializer、JacksonJsonRedisSerializer、
     * JdkSerializationRedisSerializer、OxmSerializer、StringRedisSerializer。
     * 在此我們將自己配置RedisTemplate并定義Serializer。
     *
     * @param redisConnectionFactory * @return
     */
    @Bean("getRedisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        /**
         * 配置連接工廠
         */
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        /**
         * 使用FJackson2JsonRedisSerializer序列化工具
         */
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        /**
         * 指定要序列化的域Field、set、get,以及修飾符范圍
         * ANY是都有,包括private、public
         */
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        /**
         * 指定序列化輸入的類型,類必須是非final修飾的,
         * final修飾的類,比如
         * public final class User implements Serializable{},會包異常
         */
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);


        /**
         *設(shè)置鍵(key)的序列化采用StringRedisSerializer。
         */
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        /**
         * 設(shè)置值(value)的序列化采用jackson2JsonRedisSerializer。
         */
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * 配置stringRedisTemplate序列化方式
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}

第三步,編寫util類

這段代碼是一個基于Spring框架和Redis實現(xiàn)的工具類,封裝了一些常見的操作方法。它依賴于另一個Redis配置類,通過@Autowired注解和@Qualifier注解來獲取到RedisTemplate實例,從而進行操作。

具體的操作方法有:

  • set:設(shè)置鍵值對,將value存儲到key中。
  • set:設(shè)置鍵值對并指定過期時間,將value存儲到key中,并設(shè)置過期時間。
  • remove:刪除一個或多個key對應(yīng)的值。
  • exists:判斷指定的key是否存在于緩存中。
  • get:獲取指定key對應(yīng)的值。

需要注意的是,get方法返回的是一個經(jīng)過JSON序列化的字符串,而不是原始的對象。如果要使用對象,需要在調(diào)用get方法之后進行反序列化。

package com.wangfugui.apprentice.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * RedisUtils:redis工具類
 */
@Component
public class RedisUtils {

    @Autowired
    @Qualifier("getRedisTemplate")
    private RedisTemplate redisTemplate;


    /**
     * 設(shè)置鍵值
     *
     * @Param: [key, value]
     * @return: boolean
     * @Author: MaSiyi
     * @Date: 2021/11/20
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 寫入緩存設(shè)置失效時間
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 批量刪除對應(yīng)的value
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 刪除對應(yīng)的value
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判斷緩存當中是否有對應(yīng)的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    
 /**
     * 根據(jù)key,獲取到對應(yīng)的value值
     *
     * @param key
     *            key-value對應(yīng)的key
     * @return  該key對應(yīng)的值。
     *          注: 若key不存在, 則返回null。
     *
     * @date 2020/3/8 16:27:41
     */
    public String get(String key) {
        return JSONObject.toJSONString(redisTemplate.opsForValue().get(key));
    }

}

第四步,配置yml

這是一個YAML格式的Spring Boot配置文件,配置了Redis數(shù)據(jù)庫的連接信息,包括:

  • database: Redis數(shù)據(jù)庫的編號,默認為0。
  • host: Redis服務(wù)器的IP地址。
  • port: Redis服務(wù)器的端口號。

這些配置信息會被Spring Boot自動加載并注入到對應(yīng)的Bean中,可以在代碼中使用這些Bean來連接和操作Redis數(shù)據(jù)庫。

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379

好了,就是這么的簡單,完整代碼請移至SpringBoot+Redis查看

以上就是SpringBoot集成Redis流程詳解的詳細內(nèi)容,更多關(guān)于SpringBoot集成Redis的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 基于log4j2.properties踩坑與填坑

    基于log4j2.properties踩坑與填坑

    這篇文章主要介紹了log4j2.properties踩坑與填坑方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • java實現(xiàn)Base64加密解密算法

    java實現(xiàn)Base64加密解密算法

    Base64用來將非ASCII字符的數(shù)據(jù)轉(zhuǎn)換成ASCII字符的一種方法,這篇文章主要為大家詳細介紹了java實現(xiàn)Base64加密解密算法,感興趣的小伙伴們可以參考一下
    2016-04-04
  • Android開發(fā)中Socket通信的基本實現(xiàn)方法講解

    Android開發(fā)中Socket通信的基本實現(xiàn)方法講解

    這篇文章主要介紹了Android開發(fā)中Socket通信的基本實現(xiàn)方法講解,是安卓上移動互聯(lián)網(wǎng)程序開發(fā)的基礎(chǔ),需要的朋友可以參考下
    2015-12-12
  • Json字符串內(nèi)容比較超實用教程

    Json字符串內(nèi)容比較超實用教程

    這篇文章主要介紹了Json字符串內(nèi)容比較-超實用版,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-09-09
  • 使用Spring Boot搭建Java web項目及開發(fā)過程圖文詳解

    使用Spring Boot搭建Java web項目及開發(fā)過程圖文詳解

    這篇文章主要介紹了使用Spring Boot搭建Java web項目及開發(fā)過程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • Java生成含字母和數(shù)字的6位隨機字符串

    Java生成含字母和數(shù)字的6位隨機字符串

    這篇文章主要為大家詳細介紹了Java生成含字母和數(shù)字的6位隨機字符串的相關(guān)資料,供大家參考,感興趣的朋友可以參考一下
    2016-05-05
  • Spring?Boot監(jiān)控SQL運行情況的全過程

    Spring?Boot監(jiān)控SQL運行情況的全過程

    這篇文章主要給大家介紹了關(guān)于Spring?Boot監(jiān)控SQL運行情況的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用SpringBoot具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2022-02-02
  • Springboot+Vue+axios實現(xiàn)文章收藏功能

    Springboot+Vue+axios實現(xiàn)文章收藏功能

    這篇文章主要為大家詳細介紹了Springboot+Vue+axios實現(xiàn)文章收藏功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • 淺談Spring裝配Bean之組件掃描和自動裝配

    淺談Spring裝配Bean之組件掃描和自動裝配

    本篇文章主要介紹了淺談Spring裝配Bean之組件掃描和自動裝配,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • 淺談JDK14性能管理工具之jmap和jhat

    淺談JDK14性能管理工具之jmap和jhat

    我們在寫代碼的過程中,經(jīng)常會遇到內(nèi)存泄露的問題,比如某個集合中的對象沒有被回收,或者內(nèi)存出現(xiàn)不明原因的增長。這些都是需要我們來定位的問題,我們可以使用jmap和jhat來對java程序中的內(nèi)存對象進行分析。
    2021-06-06

最新評論