使用SpringBoot和Redis的教程(共5段)

应用环境:存储令牌、…

步骤1:添加Redis的依赖关系

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

步骤2:创建一个Redis包,并添加3个Redis类。

一等文件: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序列化器
*
* 作者:一等文件
*/
public class FastJsonRedisSerializer implements RedisSerializer
{

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

private Class clazz;

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

public FastJsonRedisSerializer(Class 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 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 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 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 long setCacheList(final String key, final List dataList)
{
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}

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

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

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

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

/**
* キャッシュされたMapの取得
*
* @param key
* @return
*/
public 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 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 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 List getMultiCacheMapValue(final String key, final CollectionhKeys){return redisTemplate.opsForHash().multiGet(key, hKeys);} /*** キャッシュされた基本オブジェクトの一覧の取得** @param pattern 文字列の接頭辞* @return オブジェクトのリスト*/public Collection 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;@Configurationpublic 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。

image

步骤五:测试使用

首先,在Spring Boot的测试类中,我们通过@Autowired注解引入RedisCache。通过调用该对象的方法,可以操作Redis数据库。

请用中文将以下内容进行释义,只提供一个选项:1. “The weather is very hot today.”

@Autowired
private RedisCache redisCache;

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

Outcome: 结果

image

这是一种用于获取超过redisCache.getCacheObject(“hhh”)被IDEA调用之外的方法。同时,解压缩文件后打开redis-cli.exe,并输入get hhh指令来获取值。

image

如果您有任何疑问或需要与我分享原创内容,请随意留下评论。

广告
将在 10 秒后关闭
bannerAds