ホームページ  >  記事  >  データベース  >  SpringBoot が Redis を統合する方法

SpringBoot が Redis を統合する方法

coldplay.xixi
coldplay.xixi転載
2021-01-25 10:19:051878ブラウズ

SpringBoot が Redis を統合する方法

推奨 (無料): redis チュートリアル

今日、太陽と月が登場します。 SpringBoot を使用して Redis を統合するにはどうすればよいですか? 正直に言うと、これは比較的簡単で、インターネット上にチュートリアルがたくさんあります。まずはインターネット上の紹介を応用してみましょう。
定義

REmote DIctionary Server (Redis) は、Salvatore Sanfilippo によって作成されたキー/値ストレージ システムです。
Redis は、ANSI C 言語で書かれたオープンソースのログタイプの Key-Value データベースで、BSD プロトコルに準拠し、ネットワークをサポートし、メモリベースで永続化でき、複数の言語で API を提供します。
値には文字列、ハッシュ (マップ)、リスト、セット、ソートされたセットなどのタイプがあるため、データ構造サーバーと呼ばれることがよくあります。
reids の利点

Redis の利点のいくつかを次に示します。

非常に高速 - Redis は非常に高速で、1 秒あたり約 110,000 の設定 (SET) 操作と、1 秒あたり約 81,000 の読み取り/取得 (GET) 操作を実行できます。
豊富なデータ型のサポート - Redis は、リスト、セット、ソートされたセット、ハッシュなど、開発者が一般的に使用するほとんどのデータ型をサポートします。これにより、どのデータ型を使用するとどの問題をよりよく解決できるかがわかるため、Redis を使用してさまざまな問題を解決しやすくなります。
操作はアトミックです - すべての Redis 操作はアトミックであるため、2 つのクライアントが同時にアクセスした場合でも、Redis サーバーは更新された値を受け取ることができます。
マルチユーティリティ - Redis はマルチユーティリティであり、キャッシュ、メッセージキュー (Redis はネイティブにパブリッシュ/サブスクライブをサポート)、アプリケーション内の短期データ (Web など) などの複数のユースケースに使用できます。アプリケーションセッション、ページヒット数など。

Redis のインストール

Windows へのインストール
ダウンロード アドレス: https://github.com/MSOpenTech/redis/releases。
Redis は 32 ビットと 64 ビットをサポートします。これは、システム プラットフォームの実際の状況に応じて選択する必要があります。ここでは、Redis-x64-xxx.zip 圧縮パッケージを C ドライブにダウンロードし、解凍後、フォルダーの名前を redis に変更します。

cmd ウィンドウを開き、cd コマンドを使用してディレクトリを C:\redis
に切り替えます。redis-server.exe redis.windows.conf
を実行します。システム環境変数にredisのパスが追加されるので再度パスを入力する必要がありません 以下のredis.windows.confは省略可能です 省略した場合はデフォルトのものが使用されます有効になります。入力後、次のインターフェイスが表示されます:
SpringBoot が Redis を統合する方法

Integrated redis

前の章のプロジェクトを引き続き使用します: Springboot Integrated springcloud-config 実装 dataSource ホット デプロイメント

1. 依存関係を追加します

<!--集成redis-->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-redis</artifactid>
    <version>1.4.1.RELEASE</version>
</dependency>
<dependency>
    <groupid>com.alibaba</groupid>
    <artifactid>fastjson</artifactid>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupid>com.fasterxml.jackson.core</groupid>
    <artifactid>jackson-databind</artifactid>
</dependency>

2. 構成センターに Redis 構成を追加します

spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis服务器连接密码(默认为空)
spring.redis.password=
#连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.pool.max-idle=8
#连接池中的最小空闲连接
spring.redis.pool.min-idle=0
#连接超时时间(毫秒)
spring.redis.timeout=30000

3. 構成クラス RedisConfig

import java.lang.reflect.Method;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.PropertyAccessor; 
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
@RefreshScope
public class RedisConfig extends CachingConfigurerSupport{
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.pool.max-active}")
    private int maxActive;
    @Value("${spring.redis.pool.max-wait}")
    private int maxWait;
    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.pool.min-idle}")
    private int minIdle;
    
    @RefreshScope
    @Bean
    public KeyGenerator wiselyKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    
    @RefreshScope
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setTimeout(timeout); //设置连接超时时间
        factory.setPassword(password);
        factory.getPoolConfig().setMaxIdle(maxIdle);
        factory.getPoolConfig().setMinIdle(minIdle);
        factory.getPoolConfig().setMaxTotal(maxActive);
        factory.getPoolConfig().setMaxWaitMillis(maxWait);
        return factory;
    }
    
    @RefreshScope
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        // Number of seconds before expiration. Defaults to unlimited (0)
        cacheManager.setDefaultExpiration(10); //设置key-value超时时间
        return cacheManager;
    }
    
    @RefreshScope
    @Bean
    public RedisTemplate<string> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
        template.afterPropertiesSet();
        return template;
    }
    
    @RefreshScope
    private void setSerializer(StringRedisTemplate template) {
        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.setValueSerializer(jackson2JsonRedisSerializer);
    }
}</string>

4. RedisUtils クラス

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
@Service
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<serializable> 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 ,TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<serializable> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 批量删除对应的value
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }
    /**
     * 批量删除key
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0){
            redisTemplate.delete(keys);
        }
    }
    /**
     * 删除对应的value
     * @param key
     */
    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);
    }
    /**
     * 读取缓存
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<serializable> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    /**
     * 哈希 添加
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value){
        HashOperations<string> hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }
    /**
     * 哈希获取数据
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey){
        HashOperations<string>  hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }
    /**
     * 列表添加
     * @param k
     * @param v
     */
    public void lPush(String k,Object v){
        ListOperations<string> list = redisTemplate.opsForList();
        list.rightPush(k,v);
    }
    /**
     * 列表获取
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<object> lRange(String k, long l, long l1){
        ListOperations<string> list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }
    /**
     * 集合添加
     * @param key
     * @param value
     */
    public void add(String key,Object value){
        SetOperations<string> set = redisTemplate.opsForSet();
        set.add(key,value);
    }
    /**
     * 集合获取
     * @param key
     * @return
     */
    public Set<object> setMembers(String key){
        SetOperations<string> set = redisTemplate.opsForSet();
        return set.members(key);
    }
    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key,Object value,double scoure){
        ZSetOperations<string> zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }
    /**
     * 有序集合获取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<object> rangeByScore(String key,double scoure,double scoure1){
        ZSetOperations<string> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }</string></object></string></string></object></string></string></object></string></string></string></serializable></serializable></serializable></serializable>

5. コントローラーのテストと変更

import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.chenqi.springboot.redis.RedisUtils;
import com.chenqi.springboot.service.TestService;
@RestController
public class SpringBootController {
    
    public static final Logger log = LoggerFactory.getLogger(SpringBootController.class);
    
    @Autowired
    TestService testService;
    
    @Autowired
    private RedisUtils redisUtils;
    @RequestMapping(value = "/hello/{id}")
    public String hello(@PathVariable(value = "id") String id){
        //查询缓存中是否存在
        boolean hasKey = redisUtils.exists(id);
        String str = "";
        if(hasKey){
            //获取缓存
            Object object =  redisUtils.get(id);
            log.info("从缓存获取的数据"+ object);
            str = object.toString();
        }else{
            //从数据库中获取信息
            log.info("从数据库中获取数据");
            str = testService.test();
            //数据插入缓存(set中的参数含义:key值,user对象,缓存存在时间10(long类型),时间单位)
            redisUtils.set(id,str,10L,TimeUnit.MINUTES);
            log.info("数据插入缓存" + str);
        }
        return str;
    }
}

プロジェクトを開始し、初めてアクセスします: http://localhost:8002/hello/111
SpringBoot が Redis を統合する方法
SpringBoot が Redis を統合する方法
コンソール出力を通じて、次のことがわかります。データはデータベースから取得され、redis キャッシュに保存されます。

もう一度ブラウザを更新しましょう
SpringBoot が Redis を統合する方法
2 回目にキャッシュから読み取られることがわかります。ブラウザを継続的に更新してみましょう
SpringBoot が Redis を統合する方法
ご覧のとおり、その後、すべてがキャッシュから取得されます。

これで、redis が構成されました。

SpringBoot 統合 Redis デモのダウンロード
デモが緊急に必要な場合は、ご自身でダウンロードしてください。急いでいない場合は、メール アドレスにメッセージを残してください。通常は、 48時間以内に送信してください。

さらに関連する学習については、redis 列に注目してください。

以上がSpringBoot が Redis を統合する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はcsdn.netで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。