Spring Boot は NoSQL データベース Redis を統合します

ここに画像の説明を挿入

?? コラム推奨: Spring Boot はサードパーティ コンポーネントを統合します
?? 連載記事: [クイック スタート] SpringBoot 2.X + Mybatis-Plus を使用して CRUD を簡単に実装します(継続的に更新されます...)
?? コラム紹介:
日常の実践開発では、エンタープライズ レベルの高速構築プロジェクト フレームワーク Spring Boot を使用して、さまざまなコンポーネントを統合および開発します。このコラムでは、Spring Boot を使用して一般的に使用されるサードパーティ コンポーネントと統合する詳細な手順を要約します。交流と学習へようこそ。???

記事ディレクトリ

Spring Boot日々の開発では、プロジェクトを迅速に構築するためにこのエンタープライズ レベルのフレームワークを使用することに加えて、ビジネス データの量が大幅に増加するにつれて、メタデータ データベースに対する負荷が急激に増加しています。この文脈において、RedisこのNoSQLデータベースはすでにプロジェクト アーキテクチャ全体に不可欠な部分となっており、Spring Boot統合方法を知るRedisことは今日の開発者にとって必要なスキルとなっています。次に、統合手順について詳しく説明します。

1. 環境整備

開発を開始する前に、いくつかの環境構成を準備する必要があります。

  • jdk 1.8以降のバージョン
  • 開発ツールのアイデア
  • 依存関係を管理する Maven
  • Redis環境は、LinuxシステムにRedis環境を構築することをお勧めします

2. Spring Boot プロジェクトをビルドする

idea -> file -> Nwe -> Project図に示すように を開き、関連する構成情報を確認して入力します。

ここに画像の説明を挿入

いくつかの初期の依存構成を確認します。

ここに画像の説明を挿入

Spring Boot プロジェクトの初期化が完了しました。

ここに画像の説明を挿入

3. Redis 依存関係を導入する

Spring Boot プロジェクトをビルドした後、関連する依存関係をファイルにpom.xml導入する必要があります。redis

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

<!-- spring2.X集成redis所需common-pool2-->
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
	<version>2.6.0</version>
</dependency>

ここに画像の説明を挿入

4、レッズ関連の設定

Redis 関連の依存関係をプロジェクトに導入した後、Redis を構成し、application.propertiesRedis を構成する必要があります。

# Redis服务器地址
spring.redis.host=自己搭建的redis服务器的 IP
# Redis服务器连接端口
spring.redis.port=6379
# Redis数据库索引(默认为0)
spring.redis.database= 0
# 连接超时时间(毫秒)
spring.redis.timeout=1800000
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
# 最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=5
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0

ここに画像の説明を挿入

5. Redis 構成クラスの追加

Redis の関連構成を完了したら、Redis 構成クラスを追加します (すぐに使用できます)。

package com.zhao.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @author xiaoZhao
 * @date 2022/9/6
 * @describe
 */
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

ここに画像の説明を挿入

6、テストしてみよう

すべての環境の依存関係と構成が構築されたら、テストします。

① まず、インストールしたRedisサーバーが Redis サービスを開始していることを確認します。

ここに画像の説明を挿入

controllerクラスを書くには、前提としてSpring Boot Web以下の依存関係を導入する必要があります。

ここに画像の説明を挿入

package com.zhao.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xiaoZhao
 * @date 2022/9/6
 * @describe
 */
@RestController
@RequestMapping("/redistest")
public class RedisTestController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public String testRedis(){
        // 设置值到reids
        redisTemplate.opsForValue().set("name","jack");
        // 从redis中获取值
        String name = (String)redisTemplate.opsForValue().get("name");
        return name;
    }
}

③ Spring Boot プロジェクトを開始し、ブラウザ上のインターフェイスにリクエストを送信します。

ここに画像の説明を挿入

プロジェクトが正常に開始され、/redistestリクエストがインターフェイスに送信されます。

ここに画像の説明を挿入

リクエストが正常に送信され、データが取得され、テストが成功し、これまでのところ、Redis と Spring Boot を統合するすべての手順が完了しました。

ここに画像の説明を挿入

やっと

中級レベルのJavaエンジニアの多くはスキルアップを望んでおり、自分で成長しようとしたり、講座に参加したりすることが多いと思いますが、養成機関の1万元近い授業料は本当にストレスです。独学は効果が非効率で長く、頭打ちになりやすく技術が停滞しやすい!

そこで、「 Java 開発学習教材一式」を集めて整理し、皆さんに配りました。当初の意図も非常に単純で、独学したいけどできない友人を助けたいというものです。どこから始めればよいのかが分かり、同時に全員の負担が軽減されます。

エディターは次のように暗号化しました: aHR0cHM6Ly9kb2NzLnFxLmNvbS9kb2MvRFVrVm9aSGxQZUVsTlkwUnc==セキュリティ上の理由から、Web サイトは Base64 でエンコードされており、URL は Base64 でデコードできます。

おすすめ

転載: blog.csdn.net/m0_67265464/article/details/126774105