redis设置密码并访问

linux中设置密码
[root@iZ254lfyd6nZ ~]# cd / [root@iZ254lfyd6nZ /]# ls bin boot dev etc home lib lib64 lost+found media mnt opt proc root sbin selinux srv sys tmp usr var [root@iZ254lfyd6nZ /]# cd usr [root@iZ254lfyd6nZ usr]# ls bin etc games include lib lib64 libexec local sbin share src tmp [root@iZ254lfyd6nZ usr]# cd local [root@iZ254lfyd6nZ local]# ls aegis bin etc games include lib lib64 libexec redis redis-2.8.12.tar.gz sbin share src [root@iZ254lfyd6nZ local]# cd redis [root@iZ254lfyd6nZ redis]# ls 00-RELEASENOTES CONTRIBUTING deps INSTALL MANIFESTO redis.conf runtest-sentinel src utils BUGS COPYING dump.rdb Makefile README runtest sentinel.conf tests [root@iZ254lfyd6nZ redis]# cd src [root@iZ254lfyd6nZ src]# ls adlist.c aof.o db.o intset.h mkreleasehdr.sh rand.c redis-check-dump replication.o sha1.h t_list.o ziplist.o adlist.h asciilogo.h debug.c intset.o multi.c rand.h redis-check-dump.c rio.c sha1.o t_set.c zipmap.c adlist.o bio.c debug.o lzf_c.c multi.o rand.o redis-check-dump.o rio.h slowlog.c t_set.o zipmap.h ae.c bio.h dict.c lzf_c.o networking.c rdb.c redis-cli rio.o slowlog.h t_string.c zipmap.o ae_epoll.c bio.o dict.h lzf_d.c networking.o rdb.h redis-cli.c scripting.c slowlog.o t_string.o zmalloc.c ae_evport.c bitops.c dict.o lzf_d.o notify.c rdb.o redis-cli.o scripting.o solarisfixes.h t_zset.c zmalloc.h ae.h bitops.o endianconv.c lzf.h notify.o redisassert.h redis.h sds.c sort.c t_zset.o zmalloc.o ae_kqueue.c config.c endianconv.h lzfP.h object.c redis-benchmark redis.o sds.h sort.o util.c ae.o config.h endianconv.o Makefile object.o redis-benchmark.c redis-sentinel sds.o syncio.c util.h ae_select.c config.o fmacros.h Makefile.dep pqsort.c redis-benchmark.o redis-server sentinel.c syncio.o util.o anet.c crc64.c help.h memtest.c pqsort.h redis.c release.c sentinel.o testhelp.h valgrind.sup anet.h crc64.h hyperloglog.c memtest.o pqsort.o redis-check-aof release.h setproctitle.c t_hash.c version.h anet.o crc64.o hyperloglog.o migrate.c pubsub.c redis-check-aof.c release.o setproctitle.o t_hash.o ziplist.c aof.c db.c intset.c migrate.o pubsub.o redis-check-aof.o replication.c sha1.c t_list.c ziplist.h [root@iZ254lfyd6nZ src]# ./redis-cli 127.0.0.1:6379> get name "tanglei1234" 127.0.0.1:6379> config get requirepass 1) "requirepass" 2) "" 127.0.0.1:6379> config set requirepass newpsw OK 127.0.0.1:6379> config get requirepass (error) NOAUTH Authentication required. 127.0.0.1:6379> auth newpsw OK 127.0.0.1:6379> get name "tanglei1234" 127.0.0.1:6379> Connection closed by foreign host.

 java代码访问的redis工具类

package com.guilf.service.impl;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 



import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
 



import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
 
 
public class RedisUtil {
 
    private static final Logger log = LoggerFactory.getLogger(RedisUtil.class);
    
//    private static final Properties properties = ClassesConfigLoader.getProperties();
//    private static final String host = properties.getProperty("redis.host");
//    private static final int port = Integer.valueOf(properties.getProperty("redis.port"));
//    private static final String instanceid = properties.getProperty("redis.instanceid");
//    private static final String password = properties.getProperty("redis.password");
//    private static final int timeout = Integer.valueOf(properties.getProperty("redis.timeout", "2000"));
//    private static final int maxTotal = Integer.valueOf(properties.getProperty("redis.maxTotal", "1024"));
//    private static final int maxIdle = Integer.valueOf(properties.getProperty("redis.maxIdle", "10"));
//    private static final int maxWaitMillis = Integer.valueOf(properties.getProperty("redis.maxWaitMillis", "3000"));
//    private static final boolean testOnIdle = Boolean.valueOf(properties.getProperty("redis.testOnIdle", "true"));  //是否checkIdle
//    private static final int timeCheckIdle = Integer.valueOf(properties.getProperty("redis.timeCheckIdle", "60000"));   //每隔多少秒check一次
//    private static final int idleTimeout = Integer.valueOf(properties.getProperty("redis.idleTimeout", "300000"));     //超时时间
//    private static final int numTestsPerEvictionRun = Integer.valueOf(properties.getProperty("redis.numTestsPerEvictionRun", "1024")); //一次驱逐过程中,最多驱逐对象的个数
    
      private static final String host = "192.168.88.134";
	  private static final int port = 6379;
	 // private static final String instanceid = properties.getProperty("redis.instanceid");
	  private static final String password = "123456";
	  private static final int timeout = 2000;
	  private static final int maxTotal = 1024;
	  private static final int maxIdle = 10;
	  private static final int maxWaitMillis = 3000;
	  private static final boolean testOnIdle = true;  //是否checkIdle
	  private static final int timeCheckIdle = 60000;   //每隔多少秒check一次
	  private static final int idleTimeout = 300000;     //超时时间
	  private static final int numTestsPerEvictionRun = 1024; //一次驱逐过程中,最多驱逐对象的个数
    
    private static JedisPool pool = null;
    //private static Jedis jedis = null;
    private static Object lock = new Object();
    
    
    static {
    	init();
    }
    
    private static void init() {
    	if (null == pool) {
    		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
            config.setMaxTotal(maxTotal);
			config.setMaxIdle(maxIdle);
			config.setMaxWaitMillis(maxWaitMillis);
 
			config.setTestWhileIdle(testOnIdle);
			config.setTimeBetweenEvictionRunsMillis(timeCheckIdle);
			config.setMinEvictableIdleTimeMillis(idleTimeout);
			config.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
			synchronized (lock) {
				if (null == pool) {
					try {			            
			            
			            pool = new JedisPool(config, host, port, timeout, password);
			            log.info("init jedis pool successful!");
			        } catch (Exception e) {
			            log.error("", e);
			        }
				}
			}
		}
    	   	
    }
 
//    public static Jedis getInstance() {
//    	init();
//        
//        return jedis;
//    }
    
    /**
	 * 获取一个jedis 对象
	 * 
	 * @return
	 */
	private static Jedis getJedis() {
		if (pool == null) {
			init();
		}
		return pool.getResource();
	}
 
	/**
	 * 返还到连接池
	 * 
	 * @param pool
	 * @param redis
	 */
	private static void returnResource(Jedis redis) {
		if (redis != null) {
			redis.close();
		}
	}
	
	// 删除key
	public static Long del(String key) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			return jedis.del(key);
		} catch (Exception e) {
			log.error("操作Redis发生异常,异常详情:", e);
			return -1L;
		} finally {
			// 返还到连接池
			returnResource(jedis);
		}
		
	}
	
	public static Boolean exists(String key) {
		Jedis jedis = null;
		Boolean flag = false;
		try {
			jedis = getJedis();
			flag = jedis.exists(key);
		} catch (Exception e) {
			log.error("操作Redis发生异常,异常详情:", e);
		} finally {
			// 返还到连接池
			returnResource(jedis);
		}
 
		return flag;
	}
 
	/**
	 * 获取数据
	 * 
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		String value = null;
		Jedis jedis = null;
		try {
			jedis = getJedis();
			value = jedis.get(key);
		} catch (Exception e) {
			log.error("操作Redis发生异常,异常详情:", e);
		} finally {
			// 返还到连接池
			returnResource(jedis);
		}
		return value;
	}
 
	// 设置
	public static String set(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = getJedis();
			return jedis.set(key, value);
		} catch (Exception e) {
			log.error("操作Redis发生异常,异常详情:", e);
			return "";
		} finally {
			// 返还到连接池
			returnResource(jedis);
		}
	}
	
	// 获取Hash值
		public static String hget(String key, String field) {
			Jedis jedis = null;
			String value = null;
			try {
				jedis = getJedis();
				value = jedis.hget(key, field);
			} catch (Exception e) {
				log.error("操作Redis发生异常,异常详情:", e);
			} finally {
				// 返还到连接池
				returnResource(jedis);
			}
			return value;
		}
 
		public static Map<String, String> hgetAll(String key) {
			Jedis jedis = null;
			Map<String, String> value = null;
			try {
				jedis = getJedis();
				value = jedis.hgetAll(key);
			} catch (Exception e) {
				log.error("操作Redis发生异常,异常详情:", e);
			} finally {
				// 返还到连接池
				returnResource(jedis);
			}
			return value;
		}
 
		// 设置Hash值
		public static Long hset(String key, String field, String value) {
			Jedis jedis = null;
			try {
				jedis = getJedis();
				return jedis.hset(key, field, value);
			} catch (Exception e) {
				log.error("操作Redis发生异常,异常详情:", e);
				return -1L;
			} finally {
				// 返还到连接池
				returnResource(jedis);
			}
		}
		
		// 删除Hash值
		public static Long hdel(String key, String... fields) {
			Jedis jedis = null;
			try {
				jedis = getJedis();
				return jedis.hdel(key, fields);
			} catch (Exception e) {
				log.error("操作Redis发生异常,异常详情:", e);
				return -1L;
			} finally {
				// 返还到连接池
				returnResource(jedis);
			}
		}
		
		public static Long expire(String key, int seconds) {
			Jedis jedis = null;
			try {
				jedis = getJedis();
				return jedis.expire(key, seconds);
			} catch (Exception e) {
				log.error("操作Redis发生异常,异常详情:", e);
				return -1L;
			} finally {
				// 返还到连接池
				returnResource(jedis);
			}
		}
 
    public static void main(String[] args) {
        try {            
        	Jedis jedis = getJedis();
        	System.out.println("连接成功");
        	Set<String> keys = jedis.keys("*"); 
            Iterator<String> it=keys.iterator() ;   
            while(it.hasNext()){   
                String key = it.next();   
                System.out.println(key);   
            }
//            while (true) {
//            	String key = "ftc-ump-mid";
//                //System.out.println("before setting: " + jedis.hget(key, "attr"));
//                System.out.println(">>" + RedisUtil.hset(key, "attr", "0"));
//                RedisUtil.expire(key, 5);
//                         
//                System.out.println("after setting: " + RedisUtil.hget(key, "attr"));
//                System.out.println(">>" + RedisUtil.hdel(key, "attr"));
//                
//                System.out.println("after delete: " + RedisUtil.hget(key, "attr"));
//                
//                Thread.sleep(1000 * 10);
//            }
            
 
            //关闭退出
            //jedis.quit();
            //jedis.close();
            
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/guilf/p/9272476.html