SpringBoot は Redis をどのように統合しますか?

最初のステップは、jar パッケージをインポートすることです

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

2 番目のステップは、構成クラスを作成することです。

これは、FastJson シリアライザーを使用して RedisTemplate の Spring Bean を構成する Java クラスです。このクラスは、@Configuration アノテーションを使用してこれが構成クラスであることを識別し、@Bean アノテーションを使用してメソッドが Bean を作成するファクトリ メソッドであることを識別します。このメソッドの名前は redisTemplate で、 @ConditionalOnMissingBean の注釈が付けられています。これは、コンテキスト内に StringRedisTemplate タイプの Bean がない場合、このタイプの Bean が自動的に作成されることを意味します。このメソッドは、FastJson シリアライザーを使用してオブジェクトを保存および取得のために JSON 形式にシリアル化するように構成された RedisTemplate 型のオブジェクトを返します。メソッド内では、RedisTemplate の接続ファクトリが setConnectionFactory メソッドを通じて設定され、キーと値のシリアライザーが setKeySerializer メソッドと setValueSerializer メソッドを通じて設定されます。さらに、このクラスは、StringRedisTemplate タイプの Bean を作成するための stringRedisTemplate という名前のメソッドも提供します。


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方式: * 当我们的数据存储到Redis的时候,我们的键(key)和值(value)
     * 都是通过Spring提供的Serializer序列化到数据库的。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);


        /**
         *设置键(key)的序列化采用StringRedisSerializer。
         */
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        /**
         * 设置值(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;
    }

}
复制代码

3 番目のステップは、util クラスを作成することです。

このコードは、Spring フレームワークと Redis に基づいて実装されたツール クラスであり、いくつかの一般的な操作メソッドをカプセル化しています。これは別の Redis 構成クラスに依存し、@Autowired アノテーションと @Qualifier アノテーションを介して RedisTemplate インスタンスを取得して動作します。

具体的な操作方法は以下の通りです。

  • set: キーと値のペアを設定し、値をキーに格納します。
  • set: キーと値のペアを設定して有効期限を指定し、値をキーに保存して有効期限を設定します。
  • 削除: 1 つ以上のキーに対応する値を削除します。
  • 存在する: 指定されたキーがキャッシュに存在するかどうかを確認します。
  • get: 指定されたキーに対応する値を取得します。

get メソッドは、元のオブジェクトではなく、JSON シリアル化された文字列を返すことに注意してください。オブジェクトを使用する場合は、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;


    /**
     * 设置键值
     *
     * @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;
    }

    /**
     * 写入缓存设置失效时间
     *
     * @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;
    }

    /**
     * 批量删除对应的value
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 删除对应的value
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存当中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    
 /**
     * 根据key,获取到对应的value值
     *
     * @param key
     *            key-value对应的key
     * @return  该key对应的值。
     *          注: 若key不存在, 则返回null。
     *
     * @date 2020/3/8 16:27:41
     */
    public String get(String key) {
        return JSONObject.toJSONString(redisTemplate.opsForValue().get(key));
    }

}
复制代码

4 番目のステップは yml を設定することです

これは YAML 形式の Spring Boot 構成ファイルであり、次のような Redis データベースの接続情報を構成します。

  • データベース: Redis データベースの番号。デフォルトは 0 です。
  • host: Redis サーバーの IP アドレス。
  • port: Redis サーバーのポート番号。

これらの構成情報は Spring Boot によって自動的にロードされ、対応する Bean に挿入され、コード内でこれらの Bean を使用して Redis データベースに接続して操作できます。

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

Supongo que te gusta

Origin blog.csdn.net/2301_76607156/article/details/130557857
Recomendado
Clasificación