Java连接Redis

一、导入依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.1.0</version>
</dependency>

二、测试连接性

public class RedisTest {
	private static String HOST = "101.37.37.**";
	private static Integer HOSTIP = 6379;
	public static void main(String[] args) {
		Jedis jedis = new Jedis(HOST,HOSTIP);
		System.out.println(jedis);
		jedis.close();
	}
}

测试成功

测试成功.png


三、主从复制

public class ReidsMSTest {
	public static void main(String[] args) throws InterruptedException {
		// 创建连接
		Jedis jedis_M = new Jedis("101.37.37.**", 6379);
		Jedis jedis_S = new Jedis("101.37.37.**", 6380);
        // 遵循“配从不配主”的模式/
		jedis_S.slaveof("127.0.0.1", 6379);
        // 主机去写
		jedis_M.set("k6", "v6");
        // 内存中读写太快,防止读在写之前先完成而出现null的情况,这里做一下延迟 
		Thread.sleep(500);
        //从机去读
		System.out.println(jedis_S.get("k6"));
        //关闭连接
		jedis_M.close();
		jedis_S.close();
	}
}

主从复制测试成功

主从复制测试成功.png


四、集群连接

public class ClusterConnection {
	private static String HOST = "101.37.37.**";
	public static void main(String[] args) {
		Set<HostAndPort> nodes = new HashSet<>();
		nodes.add(new HostAndPort(HOST,7000));
		nodes.add(new HostAndPort(HOST,7001));
		nodes.add(new HostAndPort(HOST,7002));
		nodes.add(new HostAndPort(HOST,7003));
		nodes.add(new HostAndPort(HOST,7004));
		nodes.add(new HostAndPort(HOST,7005 ));
		JedisCluster cluster = new JedisCluster(nodes);
		//设置一个key
		cluster.set("k1","v1");
		//读取k1的值
		System.err.println(cluster.get("k1"));
		//输出连接对象
		System.out.println(cluster);
		//关闭连接
		cluster.close();
	}
}

集群连接成功

集群连接成功.png

五、JedisPool

说明:为什么要使用JedisPool
1、 获取Jedis实例需要从JedisPool中获取
2、 用完Jedis实例需要返还给JedisPool
3、 如果Jedis在使用过程中出错,则也需要还给JedisPool

测试案例

public class JedisPool {
	public static void main(String[] args) {
		GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
		//配置连接池的相关信息
		poolConfig.setMaxTotal(100);
		poolConfig.setMaxIdle(80);
		poolConfig.setMinIdle(20);
		poolConfig.setMaxWaitMillis(2000);
		JedisPool pool = new JedisPool(poolConfig,"101.37.37.**",6379);
		//从连接池得到链接
		Jedis jedis = pool.getResource();
		User user = new User(1,"小明",18,"湖南");
        //转换为json格式存储到Redis
		jedis.set("user:1",JSON.toJSONString(user));
		String json = jedis.get("user:1");
		User User = JSON.parseObject(json, com.tk.User.class);
        //转化为对象取出
		System.err.println(user.getAddress());
        //关闭连接
		jedis.close();
	}
}

测试结果

测试成功

posted @ 2020-06-17 17:13  Campsis-tk  阅读(92)  评论(0)    收藏  举报