zoukankan      html  css  js  c++  java
  • 使用Jedis

    前言

    借助Jedis可以在Java上操作Redis。

    Jedis

    https://mvnrepository.com/去找jar包下载即可。
    如果是maven项目:

    <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.9.0</version>
    </dependency>
    

    获取连接

    Jedis jedis = new Jedis('localhost');
    jedis.auth(password); // 如果设置了密码,就需要先执行AUTH命令,否则执行其他操作会报错
    

    连接池

    JedisPoo 类是Jedis的连接池,可以用 GenericObjectPoolConfig 类来设置连接池,这里我用了Spring。

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    import javax.annotation.PostConstruct;
    
    /**
     * Created by fjh on 2017/6/15.
     */
    @Component
    public class JedisUtils {
        private static JedisPool POOL;
        private static volatile boolean flag = false;
    
        @Value("${jedis.url:localhost}")
        private String url;
    
        @Value("${jedis.port:6379}")
        private int port;
    
        @Value("${jedis.timeout:1000}")
        private int timeOut;
    
        @Value("${jedis.auth}")
        private String auth;
    
        @Value("${jedis.pool.maxIdle:10}")
        private int maxIdle;
    
        @Value("${jedis.pool.maxTotal:100}")
        private int maxTotal;
    
        @Value("${jedis.pool.maxWaitMillis:10000}")
        private long maxWaitMillis;
    
        public static Jedis getResource() {
            return POOL.getResource();
        }
    
        //带有`@PostConstruct`注解的方法会在属性注入之后执行
        @PostConstruct
        private void init() {
            if (!flag) {
                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxIdle(maxIdle);
                config.setMaxTotal(maxTotal);
                config.setMaxWaitMillis(maxWaitMillis);
                POOL = new JedisPool(config, url, port, timeOut, auth);
                flag = true;
            }
        }
    }
    

    调用代码:

            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                System.out.println(jedis.keys("*"));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (jedis != null)
                    jedis.close();
            }
    
  • 相关阅读:
    VMwarePlayer虚拟机下centos6的静态IP配置
    C/C++ 父子进程之间的文件描述符问题
    C++ wait捕捉的信号处理WIFEXITED/WEXITSTATUS/WIFSIGNALED
    WIN7下用笔记本创建无线网
    C++ readdir、readdir_r函数
    C++ int转string(stringstream可转更多类型)
    C/C++函数中使用可变参数
    C/C++中static关键字作用总结
    Unix网络编程第三版源码编译
    Linux下初次使用github
  • 原文地址:https://www.cnblogs.com/FJH1994/p/7040423.html
Copyright © 2011-2022 走看看