• Redis (二)_ jedis的使用


    Jedis 是 Redis 官方首选的 Java 客户端开发包

    虚拟机设置

    • 查看虚拟机的ip
    ifconfig
    

    enter image description here

    • 将虚拟机的6379端口打开
    #运行下面的命令 如果是新建的一个新的 文件,你需要先安装 iptables,再打开
    vim /etc/sysconfig/iptables
    
    ## 安装命令
    yum install -y iptables-services
    
    

    enter image description here

    • 重启服务
    service iptables restart
    # 执行上面的命令,如果提示
    Redirecting to /bin/systemctl restart iptables.service
    
    # 则执行
    /bin/systemctl restart iptables.service
    
    
    • 启动redis服务 (参考上篇文章)

    java代码

    • 新建一个maven的java项目
    • 引入依赖
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.9.0</version>
                <type>jar</type>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.9</version>
            </dependency>
    
    
    • 建立测试类
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    /**
     * @Auther: curry
     * @Date: 2018/5/31 23:04
     * @Description:
     */
    
    public class Test {
        @org.junit.Test
        public void demo1(){
            Jedis jedis = new Jedis("192.168.142.128",6379);
            jedis.set("name", "test");
            String name = jedis.get("name");
            System.err.println(name);
            jedis.close();
    
        }
    
        @org.junit.Test
        public void demo2(){
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(30);
            config.setMaxIdle(10);
            JedisPool jedisPool = new JedisPool(config,"192.168.142.128",6379);
            Jedis jedis = null;
            try{
                jedis = jedisPool.getResource();
                jedis.set("name", "毛毛");
                String value = jedis.get("name");
                System.out.println(value);
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                if(jedis != null){
                    jedis.close();
                }
                if(jedisPool != null){
                    jedisPool.destroy();
                }
            }
        }
    
    }
    
    
    • 运行结果

    enter image description here

    源码下载:github

    今天电脑开着虚拟机和idea,一直内存爆表,没法运行了快。。。。

  • 相关阅读:
    PHP学习(6)——代码重用与函数编写的一些注意事项
    PHP学习(5)——字符串操作与POSIX正则
    PHP学习(4)——数组的使用
    Three.js基础探寻十——动画
    PHP学习(3)——数据的存储与检索
    Three.js基础探寻九——网格
    PHP学习(2)——操作符与迭代整理
    个人寒假作业项目《印象笔记》第一天
    《需求工程》阅读笔记2
    《需求工程》阅读笔记
  • 原文地址:https://www.cnblogs.com/zhenghengbin/p/9119728.html
Copyright © 2020-2023  润新知