Redis在开发中的使用Jedis:单机版和集群版

0、添加依赖

        
        
            redis.clients
            jedis
        

一、配置文件:applicationContext-redis.xml 



	
	
	

	
	
		
	
	
		
			
				
					
					
				
				
					
					
				
				
					
					
				
				
					
					
				
				
					
					
				
				
					
					
				
			
		
	

二、使用步骤:

package com.e3mall.jedis;

import java.util.HashSet;
import java.util.Set;

import org.junit.Test;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

public class TestJedis {
    // 单机版Redis
    @Test
    public void testJedis() {
        // 创建一个连接jedis对象 参数 host,port
        Jedis jedis = new Jedis("192.168.25.130", 6379);
        // 直接使用jedis操作redis。所有jedis命令都对应一个方法
        jedis.set("testJedis", "Hello my first Jedis");
        String string = jedis.get("testJedis");
        System.out.println(string);
        // 关闭jedis
        jedis.close();
    }

    // 单机版Redis 使用连接池单机版的Redis
    @Test
    public void testJedisPool() {
        // 创建连接池对象JedisPool;参数 host,port
        JedisPool jedisPool = new JedisPool("192.168.25.130", 6379);
        // 从连接池中获取一个连接,就是一个jedis对象
        Jedis jedis = jedisPool.getResource();
        // 使用jedis操作redis
        String string = jedis.get("testJedis");
        System.out.println(string);
        // 关闭连接,每次使用完毕后关闭连接。连接池回收资源
        jedis.close();
        // 关闭连接池jedisPool
        jedisPool.close();
    }

    // 集群版Redis
    @Test
    public void testJedisCluster() throws Exception {
        // 创建一个JedisCluster对象,有一个参数nodes是一个Set类型。Set中包含若干个HostAndPort对象
        Set nodes = new HashSet();
        nodes.add(new HostAndPort("192.168.25.130", 7001));
        nodes.add(new HostAndPort("192.168.25.130", 7002));
        nodes.add(new HostAndPort("192.168.25.130", 7003));
        nodes.add(new HostAndPort("192.168.25.130", 7004));
        nodes.add(new HostAndPort("192.168.25.130", 7005));
        nodes.add(new HostAndPort("192.168.25.130", 7006));
        JedisCluster jedisCluster = new JedisCluster(nodes);
        // 直接使用JedisCluster对象操作redis
        jedisCluster.set("testJedisCluster", "Hello My Frist JedisCluster");
        String string = jedisCluster.get("testJedisCluster");
        System.out.println(string);
        // 关闭JedisCluster对象
        jedisCluster.close();
    }
}



 

你可能感兴趣的:(redis,Java开发,项目发布)