1. 程式人生 > >java操作redis簡單示例

java操作redis簡單示例

	//Redis Server IP Port
	private static String redisServerIP 	= "192.168.100.103";
	private static int    redisServerPort	= 6379;
	
	//生產者資料儲存佇列
	private static String key_src  = "task-queue";
	private static String key_tmp  = "tmp-queue";
	
	public static class Producer implements Runnable{

		Jedis jedis = new Jedis(redisServerIP, redisServerPort);
				
		public void run() {
			while(true) {
				//使用UUID模擬產生了一個任務
				String str = UUID.randomUUID().toString();
				
				//加入佇列
				jedis.lpush(key_src, str);
				System.out.println("插入了一個新任務: " + str + "當前任務總數:" + jedis.llen(key_src));				
								
				try {
					Random random = new Random();
					Thread.sleep(random.nextInt(500) + 500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static class Consumer implements Runnable {

		Jedis jedis = new Jedis(redisServerIP, redisServerPort);
		public void run() {
			while(true) {
				//從佇列中取出任務
				String taskID = jedis.rpoplpush(key_src, key_tmp );
				if (taskID != null) {
					//處理任務
					//.....
					System.out.println("處理一個新任務: " + taskID + "當前任務總數: " + jedis.llen(key_src));
					
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}		
	}
	

	
	public static void main(String[] args) {
		
		
		new Thread(new Producer()).start();   //生產者執行緒
		new Thread(new Consumer()).start();	  //消費者執行緒
		
		try {
			Thread.sleep(Long.MAX_VALUE);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}