java操作redis简单示例

java操作redis简单示例

    初学redis,在java语言和环境下完成redis的入门学习。
        
    首先,官网下载源码,编译,安装,修改配置文件redis.conf中的三项:
    1. 注释掉 bind 127.0.0.1
    2. daemonize no 改为 daemonize yes
    3. protected-mode yes 改为protected-mode no
 
    这样的话运行 redis-server  redis.conf 默认就是在后台运行的了,而且,允许远程主机连接。

    使用jedis作为驱动来完成java程序访问redis服务器,测试代码如下:

    
Jedis jedis = new Jedis("192.168.100.103", 6379);
	res = jedis.ping();
	System.out.println(res);

     输出PONG说明连接成功!

    1. 使用redis的list数据结构完成生产者-消费者模型
	//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();
		}
	}


     2. 采用hash结构完成最简单的购物车模型
	private static String redisServerIP 	= "192.168.100.103";
	private static int    redisServerPort	= 6379;
	
	private static String hash_name  = "ShoppingCart";
	
	public static void main(String[] args) {
		
		Jedis jedis = new Jedis(redisServerIP, redisServerPort);
		
		//模拟购物车中的数据
		Map<String, String> goodsMap = new HashMap<String, String>();
		goodsMap.put("java",    "5");
		goodsMap.put("C/C++",   "3");
		goodsMap.put("Node.js", "10");
		goodsMap.put("C#",      "10");
		
		//hmset命令
		jedis.hmset(hash_name, goodsMap);
		
		System.out.println("当前共有 " + jedis.hlen(hash_name) + "个fields");
		
		List<String> fields = new ArrayList<String>();
		
		Set<String> keySet = jedis.hkeys(hash_name);
		Iterator i = keySet.iterator();
		while (i.hasNext()) {
			fields.add(i.next().toString());
		}
		
		//hmget命令
		List<String> list = jedis.hmget(hash_name, fields.get(0), fields.get(1), fields.get(2));
		System.out.println(list);
		
		//hgetall命令
		Map<String, String> map = jedis.hgetAll(hash_name);
		
		Set<Entry<String, String>> entrySet = map.entrySet();
		for (Entry<String, String> entry: entrySet) {
			System.out.println(entry.getKey() + ": " + entry.getValue());
		}
	    
		jedis.disconnect();
		
	}

    3. 事物测试
	private static String redisServerIP 	= "192.168.100.103";
	private static int    redisServerPort	= 6379;
	
	public static void main(String[] args) {
		Jedis jedis = new Jedis(redisServerIP, redisServerPort);
		long start = System.currentTimeMillis();
		//开启事物
		Transaction transaction = jedis.multi();		
		
		Map<String, String> map = new HashMap<String, String>();
    	map.put("username", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    	map.put("password", "123456");
    	map.put("age",      "25");
    	map.put("gender",   "man");
    	map.put("email",    "XXXX@xxx.com");
    	map.put("address",  "中国广东省深圳市");
    	map.put("tel",      "18888888888");
    	map.put("position", "软件工程师");
    	map.put("birth_date",   "2016-01-01 00:00:00");
    	map.put("tel",       "2016-01-01 00:00:00");
    	
    	int totalRecords = 1024;
		
	    for (int i = 0; i < totalRecords; i++) {
	    	String key = "user_" + i;
	        Response<String> result = transaction.hmset(key, map);
	    }
	    
	    //提交事物
	    List<Object> list = transaction.exec();
	    System.out.println("插入数据量: " + list.size());
	    long end = System.currentTimeMillis();
	    System.out.println("总共用时: " + ((end - start)/1000.0) + " seconds");
	    
		jedis.disconnect();
	}

    4. 采用zset完成最热商品排序功能
	private static String redisServerIP 	= "192.168.100.103";
	private static int    redisServerPort	= 6379;
	
	private static String productTopNKey = "productTopN";
	
	//商品热搜榜
	public static class ProductHotN implements Runnable {

		Jedis jedis = new Jedis(redisServerIP, redisServerPort);
		//构造热搜的商品
		String[] productTopN = {"iPhone7 Plus", "P9 Plus", "XiaoMi Note", "Vivo X7 Plus", "Galaxy Note7"};
		
		//模拟商搜索次数的变化
		public void run() {
			while (true) {
				Random random = new Random();
				//随机挑一个商品
				String product = productTopN[random.nextInt(5)];
				
				//搜索度自增1
				jedis.zincrby(productTopNKey, 1, product);	
				
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//查看商品热搜榜
	public static class HotViewer implements Runnable {

		Jedis jedis = new Jedis(redisServerIP, redisServerPort);
		int i = 1;
		public void run() {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				System.out.println("第" + i + "次获取排行榜");
				Set<Tuple> set = jedis.zrevrangeWithScores(productTopNKey, 0, -1);
				for (Tuple tuple: set) {
					System.out.println(tuple.getElement() + ": " + tuple.getScore());
				}
				
				i ++;
			}
		}
	}
	
	public static void main(String[] args) {
		new Thread(new ProductHotN()).start();
		new Thread(new HotViewer()).start();
		
		try {
			Thread.sleep(Long.MAX_VALUE);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值