0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SpringBootでRedisを使うチュートリアル(全5段)

Posted at

アプリケーション環境:トークンの保存、....

ステップ1:Redisの依存関係を追加する

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

ステップ2:redisパッケージを作成し、3つのredisクラスを追加します。

First Class file: FastJsonRedisSerializer
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * FastJsonを用いたRedisシリアライゼーション
 *
 * @author First Class file
 */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T>
{

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    static
    {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    public FastJsonRedisSerializer(Class<T> clazz)
    {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException
    {
        if (t == null)
        {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException
    {
        if (bytes == null || bytes.length <= 0)
        {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz);
    }


    protected JavaType getJavaType(Class<?> clazz)
    {
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}

Second class: RedisCache
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * Cache basic objects, Integer, String, entity classes, etc.
     *
     * @param key Cached key values
     * @param value The value of the cache
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * Cache basic objects, Integer, String, entity classes, etc.
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 有効時間の設定
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 有効時間の設定
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * キャッシュの基本オブジェクトを取得する。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 個別のオブジェクトを削除する
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    /**
     * コレクションオブジェクトの削除
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection);
    }

    /**
     * キャッシュリストデータ
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * キャッシュされたリストオブジェクトを取得する
     *
     * @param key キャッシュのキーバリュー
     * @return キーバリューに対応するキャッシュデータ
     */
    public <T> List<T> getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * キャッシュセット
     *
     * @param key キャッシュのキーバリュー
     * @param dataSet キャッシュされたデータ
     * @return データをキャッシュするためのオブジェクト
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
    {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * キャッシュされたセットを取得する
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * キャッシュMap
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * キャッシュされたMapの取得
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * Hashへのデータの預け入れ
     *
     * @param key Redis key
     * @param hKey Hash key
     * @param value key
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * ハッシュのデータを取得する
     *
     * @param key Redis Key
     * @param hKey Hash Key
     * @return Hashのオブジェクト
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * Hashからデータを削除する
     *
     * @param key
     * @param hkey
     */
    public void delCacheMapValue(final String key, final String hkey)
    {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);
    }

    /**
     * 複数のハッシュでデータを取得する
     *
     * @param key Redisキー
     * @param hKeys ハッシュキーコレクション
     * @return ハッシュオブジェクトのコレクション
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * キャッシュされた基本オブジェクトの一覧の取得
     *
     * @param pattern 文字列の接頭辞
     * @return オブジェクトのリスト
     */
    public Collection<String> keys(final String pattern)
    {
        return redisTemplate.keys(pattern);
    }
}

The third Class file:RedisConfig設定クラス
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.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);

        // StringRedisSerializer を使用して redis のキー値をシリアライズおよびデシリアライズする
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // HashのキーもStringRedisSerializerでシリアライズします。
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}

ステップ3:設定ファイルにredis設定を追加する

#yml/yaml :

# Redisデータベースのインデックス(デフォルトは0)
spring:
  redis:
    # Redisデータベースのインデックス(デフォルトは0)
    database: 0
    # Redisサーバーのアドレス
    host: 127.0.0.1
    # Redisサーバ接続ポート
    port: 6379
    jedis:
      pool:
        # コネクションプールへの最大接続数(無制限を示すには負の値を使用します。)
        max-active: 8
        # コネクションプールのブロック待ち時間の最大値(無制限を示すには負の値を使用する)
        max-wait: 1
        # コネクションプールの最大空きコネクション数
        max-idle: 8
        # コネクションプールの最小空き接続数
        min-idle: 0
    # 接続タイムアウト(ミリ秒)
    timeout: 5000
#Properties:

spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=5000

ステップ4:redisをダウンロードし、開く

  1. Redis3.0ダウンロードアドレス-蓝奏云
    2.解压后,打开其中的redis-server.exe即可
    image

ステップ5:テスト使用

SpirngBootのテストクラスで, まずは@AutowiredでRedisCacheの導入からスタート.このオブジェクトのメソッドを呼び出すことで、redisデータベースを操作します。

@Autowired
private RedisCache redisCache;

@Test
void TextRedisXX() {
    redisCache.setCacheObject("hhh", "123");
    String str = redisCache.getCacheObject("hhh");
    System.out.println(str);
}

結果:

image

によってIDEAで呼び出されるだけでなく redisCache.getCacheObject("hhh");を超えるものを取得するための方法です。,
また、解凍したファイルの中のredis-cli.exeを開くと,get hhh と入力すると 値を取得する

image

オリジナルの共有、ご質問があればお気軽にコメントを残してください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?