Redis安装和简单测试

  1. 系统环境和版本说明

操作系统选用Ubuntu 14.04, Redis的版本选取目前的最新稳定版本2.8.9. 客户端选用了Redis的Java版本jedis 2.4.2.

  1. Redis的安装步骤

a. 下载Redis的安装包

  wget http://download.redis.io/releases/redis-2.8.9.tar.gz

b. 在目录下,解压按照包,生成新的目录redis-2.8.9

  tar xvfz redis-2.8.9.tar.gz

c.  进入解压之后的目录,进行编译

    cd redis-2.8.9

    sudo make

    说明: 如果没有明显的错误,则表示编译成功

 d.  安装

    sudo make install

     说明: 一般情况下,在Ubuntu系统中,都是需要使用sudo提升权限的
     注:也可以直接用apt安装
     apt-get install redis-server
     

  e.   在安装成功之后,可以运行测试,确认Redis的功能是否正常

     sudo make test
redis.conf
daemonize yes
pidfile /var/run/redis.pid
port 6379
timeout 0
loglevel notice
logfile stdout
databases 16
save 900 10
save 300 100
save 60 10000
dbfilename dump.rdb
logfile /var/logs/redis/6379.log
maxmemory  1024000000 #一般为物理内存的3/5   
  f.  启动Redis服务

   查找Redis安装的目录:  find /  -name 'redis*'  ------ 在根目录下查找名称中含有redis的文件

  经过查找,发现Redis被安装到了/usr/local/bin/目录下。

  接下来,启动Redis服务:

      /usr/local/bin/redis-server

     ![启动redis](https://img-blog.csdn.net/20150731180519168)

说明: 从以上的截图中,可以发现启动的端口为缺省的6379. 用户可以在启动的时候,指定具体的配置文件,并在其中指定启动的端口。配置文件也配置了可以后台运行了,不知道为什么这个页面每次关掉都jedis就连接不上了,或者在本机上面用命令也ping不通.

g. 查看Redis进程

    ps -ef | grep redis

这里写图片描述

说明: 如果可以看到进程,说明启动正常,命令行输入redis-cli进入redis,输入命令ping试下是否ping的通。

  1. 简单的Redis测试程序
读者可以自行创建Eclipse项目,引入jedis的客户端包
package redistest.RedisTest;

/*
 * Copyright 2015 ireader.com All right reserved. This software is the
 * confidential and proprietary information of ireader.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with ireader.com.
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;
import redis.clients.util.SafeEncoder;

/**
 * @Descriptions redis操作工具类.
 * @date 2015年3月30日
 * @author wangliping
 */
public class JedisUtil {

//    private static final Logger LOGGER = LoggerFactory.getLogger(JedisUtil.class);

    private static final Map<String, Redis> REDIS_POOL = new ConcurrentHashMap<String, JedisUtil.Redis>();

    private static final String URI_SEPARATOR = ":";

    /**
     * 获取redis连接.
     * 
     * @param uri 连接地址(①host:port ②host:port:password)
     * @return
     */
    public static Redis get(String uri) {
        if (StringUtils.isBlank(uri)) {
            return null;
        }
        Redis redis = REDIS_POOL.get(uri);
        if (null == redis) {
            String[] config = uri.split(URI_SEPARATOR);
            if (2 == config.length) {
                redis = new Redis(config[0], Integer.parseInt(config[1]));
                REDIS_POOL.put(uri, redis);
            }
            if (3 == config.length) {
                redis = new Redis(config[0], Integer.parseInt(config[1]), config[3]);
                REDIS_POOL.put(uri, redis);
            }
        }
        return redis;
    }

    public static class Redis {

        private JedisPool jedisPool;

        public Redis(String host, int port){
            this(host, port, null);
        }

        public Redis(String host, int port, String password){
            JedisPoolConfig jedisPoolConfig = initPoolConfig();
            // 构造连接池
            jedisPool = new JedisPool(jedisPoolConfig, host, port, Protocol.DEFAULT_TIMEOUT, password);
        }

        private JedisPoolConfig initPoolConfig() {
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            // 控制一个pool最多有多少个状态为idle的jedis实例
            // jedisPoolConfig.setMaxActive(1000);
            // 最大能够保持空闲状态的对象数
            jedisPoolConfig.setMaxIdle(300);
            // 超时时间
            // jedisPoolConfig.setMaxWait(1000);
            // 在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
            jedisPoolConfig.setTestOnBorrow(true);
            // 在还会给pool时,是否提前进行validate操作
            jedisPoolConfig.setTestOnReturn(true);
            return jedisPoolConfig;
        }

        /**
         * 从池里获取一个jedis.
         * 
         * @return
         */
        private Jedis getJedis() {
            Jedis jedis = null;
            for (int i = 0; i < 5; i++) {
                try {
                    jedis = jedisPool.getResource();
                    break;
                } catch (Exception e) {
//                    LOGGER.error("get redis master failed!", e);
                    jedisPool.returnBrokenResource(jedis);
                }
            }
            return jedis;
        }

        /**
         * setex 设置值 并指定键值对应的有效期 单位为秒<br>
         * 如果key 存在 覆盖旧值 <br>
         */
        public void setex(String key, int seconds, String value) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.setex(key, seconds, value);
                // 还会到连接池
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * set 如果存在相同的key 覆盖旧值<br>
         */
        public boolean set(String key, String value) {
            // 从池中获取一个jedis实例
            Jedis jedis = getJedis();
            try {
                String stateCode = jedis.set(key, value);
                return "OK".equals(stateCode);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * set 如果存在相同的key 覆盖旧值<br>
         */
        public boolean set(String key, byte[] value) {
            // 从池中获取一个jedis实例
            Jedis jedis = getJedis();
            try {
                String stateCode = jedis.set(SafeEncoder.encode(key), value);
                return "OK".equals(stateCode);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * setnx 如果key存在 不做任何操作 返回0, <br>
         * 如果key不存在 设置值成功 返回1 <br>
         */
        public Long setnx(String key, String value) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.setnx(key, value);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }

        }

        /**
         * setnx 如果key存在 不做任何操作 返回false, <br>
         * 缓存时间以毫秒为单位 <br>
         */
        public boolean setnxpx(String key, String value, long ttl) {
            // 从池中获取一个jedis实例
            Jedis jedis = getJedis();
            try {
                String stateCode = jedis.set(key, value, "NX", "PX", ttl);
                return "OK".equals(stateCode);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * setex 如果key存在 覆盖旧值,原有ttl覆盖为新ttl<br>
         * 缓存时间以毫秒为单位 <br>
         */
        public boolean setxxpx(String key, String value, long ttl) {
            // 从池中获取一个jedis实例
            Jedis jedis = getJedis();
            try {
                String stateCode = jedis.set(key, value, "XX", "PX", ttl);
                return "OK".equals(stateCode);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * setrange 通过key 和 offset 替换value <br>
         * 例如:setex - > setex_value jedis.setrange("setex", 6, "Setrange") <br>
         * 替换为 setex_Setrange <br>
         */
        public void setrange(String key, int offset, String value) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.setrange(key, offset, value);
                // 还会到连接池
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * mset 同时设置一个或多个 key-value对。 如果某个key-value 存在 会用新值覆盖原来的旧值, 总是成功, 成功返回OK <br>
         */
        public void mset(String... keysvalues) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.mset(keysvalues);
                // 还会到连接池
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * msetnx 同时设置一个或多个 key-value对。 如果某个key-value存在 返回0 所有操作都会回滚, 如果成功 返回ok <br>
         */
        public void msetnx(String... keysvalues) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                jedis.msetnx(keysvalues);
                // 还会到连接池
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * get 通过key 获取对应的value 如果key不存在 返回nil <br>
         */
        public String get(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.get(key);
                // 还会到连接池
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 获取key生存时间,以秒为单位<br>
         */
        public Long ttl(String key) {
            Jedis jedis = null;
            try {
                // 从池中获取一个jedis实例
                jedis = getJedis();
                return jedis.ttl(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * get 通过key 获取对应的value 如果key不存在 返回nil <br>
         */
        public byte[] getBinary(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.get(SafeEncoder.encode(key));
            } finally {
                // 还回到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * getset 通过key 获取对应的value 然后通过key 设置新的value <br>
         */
        public String getSet(String key, String value) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.getSet(key, value);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 返回key对应的value 在由start 和 end 两个偏移量截取 <br>
         */
        public String getrange(String key, int startOffset, int endOffset) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.getrange(key, startOffset, endOffset);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 返回多个key 对应的value <br>
         */
        public List<String> mget(String... keys) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.mget(keys);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 对key对应的value 做+1操作 返回+1后的新值 <br>
         */
        public Long incr(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.incr(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 对key对应的value 加指定值 返回新值 如果key不存在 认为原来的value为0 <br>
         */
        public Long incrBy(String key, int integer) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.incrBy(key, integer);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 对key对应的value 做-1操作 返回新值 <br>
         */
        public Long decr(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.decr(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 对key对应的value 减去指定值 返回新值 如果key不存在 认为原来的value为0 <br>
         */
        public Long decrBy(String key, int integer) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.decrBy(key, integer);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 给指定的key的值追加, 返回新字符串的长度 <br>
         */
        public Long append(String key, String value) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.append(key, value);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 取得指定key的value值的长度 <br>
         */
        public Long strlen(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.strlen(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 删除指定key<br>
         */
        public Long del(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.del(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 右侧入列 <br>
         */
        public Long rpush(String key, String... strings) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.rpush(key, strings);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 左侧出列<br>
         */
        public String lpop(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.lpop(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 队列长度
         */
        public Long llen(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.llen(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }
        
        /**
         * 返回列表 key 中指定区间内的元素<br>
         * 区间以偏移量 start 和 stop 指定
         */
        public List<String> lrange(String key,long start,long end){
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.lrange(key, start, end);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }
        
        /**
         * 返回列表 key 中指定区间内的元素<br>
         * 区间以偏移量 start 和 stop 指定
         */
        public boolean  ltrim(String key,long start,long end){
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                String stateCode = jedis.ltrim(key, start, end);
                return "OK".equals(stateCode);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 检测是否存在<br>
         */
        public boolean exists(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.exists(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * set 增加<br>
         */
        public Long sadd(String key, String... members) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.sadd(key, members);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * set 是否存在 类似 list contains<br>
         */
        public Boolean sismember(String key, String member) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.sismember(key, member);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * set 随机获取一个值.
         * 
         * @param key
         * @return
         */
        public String srandmember(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.srandmember(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * set 长度<br>
         */
        public Long scard(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.scard(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * set 所有值<br>
         */
        public Set<String> smembers(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.smembers(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * set 删除<br>
         */
        public Long srem(String key, String... members) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.srem(key, members);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * map 增加<br>
         */
        public String hmset(String key, Map<String, String> hash) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.hmset(key, hash);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 取出map中的字段值<br>
         */
        public List<String> hmset(String key, String... fields) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.hmget(key, fields);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * 删除map中的某一个键值<br>
         */
        public Long hdel(String key, String... fields) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.hdel(key, fields);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * map中的所有键值<br>
         */
        public Set<String> hkeys(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.hkeys(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }

        /**
         * map中的所有value<br>
         */
        public List<String> hvals(String key) {
            // 从池中获取一个jedis实例
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.hvals(key);
            } finally {
                // 还会到连接池
                jedisPool.returnResource(jedis);
            }
        }
    }

    static {
        Thread cleaner = new Thread(new Cleaner());
        cleaner.setDaemon(true);
        cleaner.start();
    }

    private static class Cleaner implements Runnable {

        public void run() {
            List<String> errors = new ArrayList<String>();
            while (true) {
                try {
                    Thread.sleep(60000);
                    if (REDIS_POOL.size() <= 0) {
                        continue;
                    }
                    for (Map.Entry<String, Redis> entry : REDIS_POOL.entrySet()) {
                        try {
                            Redis redis = entry.getValue();
                            if (null == redis) {
                                errors.add(entry.getKey());
                            }
                            redis.get("redis");
                        } catch (Exception e) {
                            errors.add(entry.getKey());
//                            LOGGER.warn("redis connection failure!!uri:{}", entry.getKey());
                        }
                    }

                    if (errors.isEmpty()) {
                        continue;
                    }

                    for (String uri : errors) {
                        REDIS_POOL.remove(uri);
                        // get(uri);
                    }
                    errors.clear();
                } catch (Exception e) {
//                    LOGGER.error("redis daemon thread exception!!!message:" + e.getMessage(), e);
                }
            }
        }

    }
}

注:redis 远程连接时报错 Exception in thread “main” redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect (redis 安装在ubuntu 系统)
1.首先,我们要把防火墙禁用掉
2.安装redis时,Redis 的配置文件默认是绑定本地ip的,所以我们要去系统中找到bind 127.0.0.1,然后把它注释掉,那么就可以连接上了
3.下面是redis.conf配置文件,看到bind 127.0.0.1吗?就是他,搞我们连接不上,注释掉吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值