1. 程式人生 > >Redis執行緒池及分散式

Redis執行緒池及分散式

在大型的網際網路網站中,單機的Redis往往是不支援大併發的,很多時候都需要分散式以及叢集來降低伺服器崩潰造成整個網站的停止執行,所以,Redis也是需要進行分散式以及叢集去防範這種現象的發生。

我們需要一些依賴:

<span style="white-space:pre">	</span><dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.13</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.13</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.jmock</groupId>
			<artifactId>jmock-junit4</artifactId>
			<version>2.8.1</version>
		</dependency>
		<dependency>
			<groupId>org.jmock</groupId>
			<artifactId>jmock</artifactId>
			<version>2.8.1</version>
		</dependency>
		<dependency>
			<groupId>org.jmock</groupId>
			<artifactId>jmock-legacy</artifactId>
			<version>2.8.1</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.8.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
			<version>2.4.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>
	</dependencies>

1、首先,建立一個Config

package jmust.redis.RedisPool;

/**
 * 
 * @author LK
 *
 */
public class RedisConfig {

	private static final int redisPort = 6379;
	private static final String redisAdress = "127.0.0.1,192.168.100.117";
	private static final int maxIdle = 10;
	private static final int maxTotal = 30;
	private static final int maxWaitMillis = 3000;
	private static final int db = 3;
	private static final String scheme = "http://";
	
	public static int getRedisport() {
		return redisPort;
	}
	public static String getRedisadress() {
		return redisAdress;
	}
	public static int getMaxidle() {
		return maxIdle;
	}
	public static int getMaxtotal() {
		return maxTotal;
	}
	public static int getMaxwaitmillis() {
		return maxWaitMillis;
	}
	public static int getDb() {
		return db;
	}
	public static String getScheme() {
		return scheme;
	}
	
}

2、Redis工具類
package jmust.redis.RedisPool;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

/**
 * 
 * @author LK
 *
 */
public class RedisUtil {
	private static final Logger log = LoggerFactory.getLogger(RedisUtil.class);
	public static ShardedJedisPool pool;
	
	static {
		createJedisPool();
	}
	
	/**
	 * init jedis pool
	 */
	private static void createJedisPool(){
		try{
			List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
			String[] address = (String[])getRedisAddress(RedisConfig.getRedisadress());
			for (int i = 0; i <address.length; i++) {
				//shards.add(new JedisShardInfo(address[i],RedisConfig.getRedisport()));
				shards.add(new JedisShardInfo(RedisConfig.getScheme()+address[i]+":"+RedisConfig.getRedisport()+
						"/"+RedisConfig.getDb()));
			}
			// 生成連線池配置資訊
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxIdle(RedisConfig.getMaxidle());
			config.setMaxTotal(RedisConfig.getMaxtotal());
			config.setMaxWaitMillis(RedisConfig.getMaxwaitmillis());
			// 在應用初始化的時候生成連線池
			pool = new ShardedJedisPool(config, shards);
		}catch(Exception e){
			log.error("createJedisPool ",e);
		}
	}
	
	/**
	 * get pool
	 * @return
	 */
	public static ShardedJedisPool getShardedPool(){
		if(pool == null){
			createJedisPool();
		}
		return pool;
	}
	
	public static ShardedJedis getShardedJedis(){
		ShardedJedis jedis = null;
		try{
			jedis = getShardedPool().getResource();
		}catch(Exception e){
			log.error("getPool().getResource() error", e);
		}
		return jedis;
	}
	
	private static  Object getRedisAddress(String redisAddress){
		Object address = null;
		if(StringUtils.isNoneBlank(redisAddress)&&redisAddress.contains(",")){
			address = redisAddress.split(",");
		}else{
			address = redisAddress.toCharArray();
		}
		return address;
	}
	

}

3、單元測試
package jmust.redis.RedisPool;

import org.junit.Test;

import redis.clients.jedis.ShardedJedis;

/**
 * Unit test for simple RedisUtil.
 */
public class RedisTest 
{
	@Test
	public void redisTest(){
		// 在業務操作時,從連線池獲取連線
		ShardedJedis client = null;
		try {
			client = RedisUtil.getShardedPool().getResource();
		    // 執行指令
		    String result = client.set("key-string212", "Hello, Redis!");
		    System.out.println( String.format("set指令執行結果2:%s", result) );
		    String value = client.get("key-string212");
		    System.out.println( String.format("get指令執行結果2:%s", value) );
		} catch (Exception e) {
		    // TODO: handle exception
		} finally {
		    // 業務操作完成,將連線返回給連線池
		    if (null != client) {
		    	RedisUtil.getShardedPool().getResource().close();
		    }
		}
	}
}