zoukankan      html  css  js  c++  java
  • 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);//设置一个keycluster.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格式存储到Redisjedis.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();}}

    测试结果

    测试成功

  • 相关阅读:
    匈牙利算法-二分图的最大匹配
    UOJ 407(IOI2018 D1T3)
    UOJ 460
    UOJ 405(IOI2018 D1T1)
    Codeforces 1110E
    2.文件结构
    1.常用快捷键
    Python3.x和Python2.x的差异
    javascript 常用内置对象
    94. Binary Tree Inorder Traversal(非递归实现二叉树的中序遍历)
  • 原文地址:https://www.cnblogs.com/yangzhuxian/p/13370930.html
Copyright © 2011-2022 走看看