SpringBoot が Redis を統合してホットスポット データ キャッシュを実装する方法

王林
リリース: 2023-05-27 14:07:11
転載
1489 人が閲覧しました

Redis を Java に統合するためのテスト環境として IDEA SpringBoot を使用します

まず、Redis の Maven 依存関係をインポートする必要があります


		
			org.springframework.boot
			spring-boot-starter-data-redis
		
ログイン後にコピー

次に、構成ファイルで Redis 構成情報を構成します。.yml ファイル形式を使用します

# redis配置
spring:
  redis:
    # r服务器地址
    host: 127.0.0.1
    # 服务器端口
    port: 6379
    # 数据库索引(默认0)
    database: 0
    # 连接超时时间(毫秒)
    timeout: 10s
    jedis:
      pool:
        # 连接池中的最大空闲连接数
        max-idle: 8
        # 连接池中的最小空闲连接数
        min-idle: 0
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 8
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
ログイン後にコピー

redis のカスタム構成を作成します

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.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
@Configuration
public class RedisConfigurer extends CachingConfigurerSupport {
 
    /**
     * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
     */
    @Bean
    public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        // 配置redisTemplate
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        // 设置序列化
        Jackson2JsonRedisSerializer redisSerializer = getRedisSerializer();
        // key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // value序列化
        redisTemplate.setValueSerializer(redisSerializer);
        // Hash key序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash value序列化
        redisTemplate.setHashValueSerializer(redisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
 
    /**
     * 设置Jackson序列化
     */
    private Jackson2JsonRedisSerializer getRedisSerializer() {
        Jackson2JsonRedisSerializer redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        redisSerializer.setObjectMapper(om);
        return redisSerializer;
    }
}
ログイン後にコピー

次に、Redis データベースを構成するために RedisUtil を作成する必要があります操作

package com.zyxx.test.utils;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 
/**
 * @ClassName RedisUtil
 * @Author 
 * @Date 2019-08-03 17:29:29
 * @Version 1.0
 **/
@Component
public class RedisUtil {
 
    @Autowired
    private RedisTemplate template;
 
    /**
     * 读取数据
     *
     * @param key
     * @return
     */
    public String get(final String key) {
        return template.opsForValue().get(key);
    }
 
    /**
     * 写入数据
     */
    public boolean set(final String key, String value) {
        boolean res = false;
        try {
            template.opsForValue().set(key, value);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
    /**
     * 根据key更新数据
     */
    public boolean update(final String key, String value) {
        boolean res = false;
        try {
            template.opsForValue().getAndSet(key, value);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
    /**
     * 根据key删除数据
     */
    public boolean del(final String key) {
        boolean res = false;
        try {
            template.delete(key);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
    
	/**
     * 是否存在key
     */
    public boolean hasKey(final String key) {
        boolean res = false;
        try {
            res = template.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
	/**
     * 给指定的key设置存活时间
     * 默认为-1,表示永久不失效
     */
    public boolean setExpire(final String key, long seconds) {
        boolean res = false;
        try {
            if (0 < seconds) {
                res = template.expire(key, seconds, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
    /**
     * 获取指定key的剩余存活时间
     * 默认为-1,表示永久不失效,-2表示该key不存在
     */
    public long getExpire(final String key) {
        long res = 0;
        try {
            res = template.getExpire(key, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
 
	/**
     * 移除指定key的有效时间
     * 当key的有效时间为-1即永久不失效和当key不存在时返回false,否则返回true
     */
    public boolean persist(final String key) {
        boolean res = false;
        try {
            res = template.persist(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
    
}
ログイン後にコピー

最後に、単体テストを使用して、RedisUtil で作成した Redis データベースを操作するメソッドを検出できます

package com.zyxx.test;
 
import com.zyxx.test.utils.RedisUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTest {
 
    @Resource
    private RedisUtil redisUtil;
 
    @Test
    public void setRedis() {
        boolean res = redisUtil.set("jay", "周杰伦 - 《以父之名》");
        System.out.println(res);
    }
 
    @Test
    public void getRedis() {
        String res = redisUtil.get("jay");
        System.out.println(res);
    }
 
 
    @Test
    public void updateRedis() {
        boolean res = redisUtil.update("jay", "周杰伦 - 《夜的第七章》");
        System.out.println(res);
    }
 
    @Test
    public void delRedis() {
        boolean res = redisUtil.del("jay");
        System.out.println(res);
    }
 
	@Test
    public void hasKey() {
        boolean res = redisUtil.hasKey("jay");
        System.out.println(res);
    }
 
	@Test
    public void expire() {
        boolean res = redisUtil.setExpire("jay", 100);
        System.out.println(res);
    }
 
    @Test
    public void getExpire() {
        long res = redisUtil.getExpire("jay");
        System.out.println(res);
    }
 
	@Test
    public void persist() {
        boolean res = redisUtil.persist("jay");
        System.out.println(res);
    }
    
}
ログイン後にコピー
  • redis-desktop- を使用することをお勧めします。データベース内のデータの Redis 表示ツールとしてのマネージャー

  • この時点で、Redis を日常のプロジェクトに統合する基本的な使用法は完了しましたが、実際のプロジェクトでは、より複雑な使用法が含まれる可能性があります。ビジネス ニーズに応じて Redis の使用を調整できます。

以上がSpringBoot が Redis を統合してホットスポット データ キャッシュを実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:yisu.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!