ホームページ  >  記事  >  Java  >  JavaのRedisクラスタ動作例を詳しく解説

JavaのRedisクラスタ動作例を詳しく解説

零下一度
零下一度オリジナル
2017-05-26 14:38:303410ブラウズ

Redis クラスターの構築については、私の他の記事 Redis クラスターの構築と簡単な使い方を参照してください

Redis とは何ですか、何ができるのですか

Redis は、オープンソース (BSD ライセンス) のメモリ ストレージ データ構造サーバーです。利用可能 データベース、キャッシュ、メッセージ キュー ブローカーと連携します。文字列、ハッシュ テーブル、リスト、セット、順序付きセット、ビットマップ、ハイパーログログ、およびその他のデータ型をサポートします。組み込みのレプリケーション、Lua スクリプト、LRU エビクション、トランザクション、およびさまざまなレベルのディスク永続化機能により、Redis Sentinel による高可用性と Redis Cluster による自動パーティショニングが提供されます。 (Redis公式サイトより抜粋)

インメモリデータベースとして、現代のインターネットWebシステムでは、Redisは今でも主にキャッシュとして使用されています。大規模なインターネット Web システムには高いパフォーマンスが要求され、フロントエンドとデータ層の間にデータ キャッシュを追加することが重要な手段の 1 つとなっています。その 2 つのテクノロジは Redis と Memcached です。それはこの記事の内容ではありません。この記事では主に、Java Web が Redis と Redis クラスターをどのように操作するかについて説明します。

一般的な Java プログラムは Redis を操作します

Redis は複数の言語でクライアントを提供します。Java で最も人気のあるものは Jedis です。にアクセスしてソース コードとその使用方法を確認してください。現在、Jedis の最新バージョンは 2.9.0 です。スタンドアロン マシンでもクラスターでも、Jedis には非常に詳細な手順とサンプル コードが用意されています。ここでは簡単に説明します。パッケージ管理に Maven を使用する場合、次のように、jedis パッケージを参照する必要があります。 この例では、次のように最新の 2.9.0 バージョンを使用します。 mvc、まずは Spring mvc フレームワークをセットアップします。以下は Spring mvc 環境が構築されていることを前提としています。この例では、Spring バージョンは 4.3.2 RELEASE です。 Spring に関する Maven リファレンスは次のとおりです:

  redis.clients      jedis      2.9.0  
操作 Redis 单机
import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig; /** * Created by fengdezitai on 2016/10/9. */public class JedisClient {     private static final String host= "192.168.31.121";     private static final JedisClient jedisClient = new JedisClient();     private Jedis jedis = null;    /**     * 私有构造函数     */    private JedisClient(){}     public static JedisClient getInstance(){        return jedisClient;    }     private JedisPoolConfig getPoolConfig(){        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();        jedisPoolConfig.setMaxIdle(10);        jedisPoolConfig.setMaxTotal(100);        jedisPoolConfig.setMaxWaitMillis(3000);        return jedisPoolConfig;    }     /**     * 添加     * @param key     * @param value     * @return     * @throws Exception     */    public Boolean add(String key,String value) throws Exception{        JedisPool pool = new JedisPool(getPoolConfig(),host);        Jedis jedis = null;        try {            jedis = pool.getResource();            if(jedis.exists(key)){                throw new Exception(String.format("key (%s) 已存在 ",key));            }            jedis.set(key,value);         }catch (Exception e){            throw e;        }        finally {            if(jedis!=null){                jedis.close();            }        }        pool.destroy();        return true;    }     /**     * 获取值     * @param key     * @return     * @throws Exception     */    public String get(String key) throws Exception{        JedisPool pool = new JedisPool(getPoolConfig(),host);        Jedis jedis = null;        String result = "";        try {            jedis = pool.getResource();            result = jedis.get(key);        }catch (Exception e){            throw e;        }        finally {            if(jedis!=null){                jedis.close();            }        }        pool.destroy();        return result;    }     public static void main(String[] args) {        JedisClient jedisClient = JedisClient.getInstance();        try {            /*Boolean result = jedisClient.add("hello", "redis1");            if(result){                System.out.println("success");            }*/             System.out.println(jedisClient.get("hello"));        }catch (Exception e){            e.printStackTrace();        }    }}

Redis をスタンドアロンで操作します

インジェクションの実装には Jedis のみを使用します (spring-data-redis の下のリファレンスとは異なります) 前の JedisClient コードを取得して引用するだけです。 Redis サービスへのアクセスは Spring mvc に統合できます。実装する必要があるのは 1 つだけです。 Service コードは以下の通りです:

import redis.clients.jedis.*;
import java.util.HashSet;
import java.util.Set;
 
/**
 * Created by fengdezitai on 2016/10/13.
 */
public class JedisClusterClient {
 
    private static int count = 0;
 
    private static final JedisClusterClient redisClusterClient = new JedisClusterClient();
 
    /**
     * 私有构造函数
     */
    private JedisClusterClient() {}
 
    public static JedisClusterClient getInstance() {
        return redisClusterClient;
    }
 
    private JedisPoolConfig getPoolConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(1000);
        config.setMaxIdle(100);
        config.setTestOnBorrow(true);
        return config;
    }
 
    public void SaveRedisCluster() {
        Set jedisClusterNodes = new HashSet();
        jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7000));
        jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7001));
        jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7002));
        jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7003));
        jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7004));
        jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7005));
 
        JedisCluster jc = new JedisCluster(jedisClusterNodes,getPoolConfig());
        jc.set("cluster", "this is a redis cluster");
        String result = jc.get("cluster");
        System.out.println(result);
    }
 
    public static void main(String[] args) {
        JedisClusterClient jedisClusterClient = JedisClusterClient.getInstance();
        jedisClusterClient.SaveRedisCluster();
    }
}  

Controller は以下のように実装されています:

4.3.2.RELEASE 
    
          org.springframework      spring-core      ${spring.version}                        commons-logging          commons-logging                   
          org.springframework      spring-web      ${spring.version}     
          org.springframework      spring-oxm      ${spring.version}     
          org.springframework      spring-tx      ${spring.version}     
          org.springframework      spring-jdbc      ${spring.version}     
          org.springframework      spring-webmvc      ${spring.version}                        commons-logging          commons-logging                   
          org.springframework      spring-aop      ${spring.version}     
          org.springframework      spring-context-support      ${spring.version}     
 
          org.springframework      spring-test      ${spring.version}

統合には spring-data-redis パッケージを使用します

上記は私が実装したインジェクションです。 ここでは spring-data-redis を使用しています。 Maven パッケージは次のように引用されており、バージョンは最新バージョン 1.7.2.RELEASE:

import org.springframework.stereotype.Service;
import util.JedisClient;
 
/**
 * Created by fengdezitai on 2016/10/9.
 */
@Service
public class RedisService {
 
    public String get(String key) throws Exception{
        JedisClient jedisClient = JedisClient.getInstance(); //上面实现的JedisClient
        String result = "";
        try {
            result = jedisClient.get("hello");
        }catch (Exception e){
            throw e;
        }
        return result;
    }
}

spring-data-redis を使用すると、インジェクション プロセスを自分で実装する必要がなくなります。提供される一部の構成を通じて、RedisTemplate 構成、JedisConnectionFactory 構成を実現でき、JedisConnectionFactory を通じて、接続プールのパラメーター、Redis サーバー、ポート、パスワード、データベース インデックスなどを構成できます。は注入された Bean であり、RedisTemplate によって自動的に注入されたエンティティを使用して、一連の Redis 操作を実行できます。詳細については、構成を参照してください。

redis サービス属性構成ファイル:

@Controller
@RequestMapping(value = "redisAllInOne")
public class RedisAllInOneController {
 
    @Autowired
    private RedisService redisService;
 
    @RequestMapping(value = "get",method = RequestMethod.GET)
    @ResponseBody
    public Object getByMyService(String key){
        try {
            String result = redisService.get(key);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}  

次に、Spring 構成で上記のファイルを引用します。ファイル:

上記の構成について説明します:


poolConfig は Redis 接続プールを構成し、次に 2 つの JedisConnectionFactory と RedisTemplate を構成するため、次のようなシナリオに応じて異なる Redis 接続を構成できます。一貫性のないタイムアウト要件、データベース 0 ~ 15 には異なるデータが保存される可能性があるなど。ここではデータベース 1 と 2 が構成されており、commonRedisTemplate を呼び出すとデータベース 1 に保存され、cacheRedisTemplate を呼び出すとデータベース 2 に保存されます。

その後、次のように、これら 2 つの RedisTemplate をサービス層に挿入して参照できます:

      org.springframework.data      spring-data-redis      1.7.2.RELEASE

最後にコントローラーで呼び出します

redis.maxIdle=300redis.maxWait=3000redis.testOnBorrow=trueredis.host=192.168.31.121redis.port=6379redis.password=passwordredis.timeout=3000
spring-data-redis xml 配置文件 redis-context.xml:                                                              -->                                                                                                          -->

Redis クラスターを操作するには

Jedis を使用して自分でインジェクションを実装するだけです (別の以下のリファレンス spring-data-redis より)

以前の JedisClusterClient コードを取得して参照するだけで、Redis にアクセスするための Service を実装するだけで、Spring mvc に統合できます。サービスのコードは次のとおりです:

import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
 
import javax.annotation.Resource;
import java.io.*;
 
@Repository
public class RedisCache {  
    @Resource(name = "cacheRedisTemplate")
    private RedisTemplate

最後に、コントローラーで実装されたサービスを呼び出します

@Autowired
private RedisCache redisCache;
 
 
@RequestMapping(value = "get", method = RequestMethod.GET)
@ResponseBody
public Object getByMyService(String key) {
    try {
        String result = redisService.get(key);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
@RequestMapping(value = "save", method = RequestMethod.GET)
@ResponseBody
public Object save() {
    Token token = new Token();
    token.setAccess_token("token");
    token.setExpires_in(1000);
    try {
        redisCache.put("token", token);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "ok";
}  

注:

バージョンの問題、統合操作 Reid クラスターに spring-data-redis を使用する場合、spring-data-redis の最新バージョンのみが必要です。 data-redis が利用できる 1.7 にはクラスター操作のみが含まれており、最新の spring-data-redis の一部の関数には Spring mvc バージョンにいくつかの制限があるため、Spring mvc の上位バージョンを選択するようにしてください。

格納された値がエンティティ オブジェクトの場合は、Serializable インターフェイスを実装する必要があります

[関連する推奨事項]

1. Spring フレームワーク アノテーションの使用コード例の詳細な説明

2. Spring および Java トランザクション管理Hibernate コードの詳細な説明

3.

Spring Boot を使用した Restful プログラムの開発に関するサンプル チュートリアルを共有します

4. Spring mvc でサポートされている 7 つの return メソッドの詳細な説明

5. アスペクトに基づいた Spring の強化された実装例の詳細な説明

6. Java Spring の例の PHPRPC

8. Spring での Elasticsearch の使用例の詳細な説明

以上がJavaのRedisクラスタ動作例を詳しく解説の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。