zoukankan      html  css  js  c++  java
  • Java连接Redis

    在Java程序中使用Redis之前,需要确保在机器上安装了Redis的Java驱动程序和Java环境。可以先在将Java电脑上并配置好环境。

    安装

    现在,让我们看看如何设置Redis Java驱动程序。

    Java连接到Redis服务器

    请参考以下一个简单的示例代码

    import redis.clients.jedis.Jedis; 
    
    public class RedisJava { 
       public static void main(String[] args) { 
          //Connecting to Redis server on localhost 
          Jedis jedis = new Jedis("localhost"); 
          System.out.println("Connection to server sucessfully"); 
          //check whether server is running or not 
          System.out.println("Server is running: "+jedis.ping()); 
       } 
    }

    现在,编译并运行上面的程序来测试与Redis服务器的连接。可以根据需要更改路径。假设jedis.jar的当前版本在当前路径中可以使用。 执行上面代码,将生成以下结果 -

    $javac RedisJava.java 
    $java RedisJava 
    Connection to server sucessfully 
    Server is running: PONG

    Redis Java字符串示例

    import redis.clients.jedis.Jedis; 
    
    public class RedisStringJava { 
       public static void main(String[] args) { 
          //Connecting to Redis server on localhost 
          Jedis jedis = new Jedis("localhost"); 
          System.out.println("Connection to server sucessfully"); 
          //set the data in redis string 
          jedis.set("tutorial-name", "Redis tutorial"); 
          // Get the stored data and print it 
          System.out.println("Stored string in redis:: "+ jedis.get("tutorialname")); 
       } 
    }
    

    执行上面代码,将生成以下结果 -

    $javac RedisStringJava.java 
    $java RedisStringJava 
    Connection to server sucessfully 
    Stored string in redis:: Redis tutorial
    

    Redis Java列表示例

    import redis.clients.jedis.Jedis; 
    
    public class RedisListJava { 
       public static void main(String[] args) { 
          //Connecting to Redis server on localhost 
          Jedis jedis = new Jedis("localhost"); 
          System.out.println("Connection to server sucessfully"); 
    
          //store data in redis list 
          jedis.lpush("tutorial-list", "Redis"); 
          jedis.lpush("tutorial-list", "Mongodb"); 
          jedis.lpush("tutorial-list", "Mysql"); 
          // Get the stored data and print it 
          List<String> list = jedis.lrange("tutorial-list", 0 ,5); 
    
          for(int i = 0; i<list.size(); i++) { 
             System.out.println("Stored string in redis:: "+list.get(i)); 
          } 
       } 
    }
    

    执行上面代码,将生成以下结果 -

     
    $javac RedisListJava.java 
    $java RedisListJava 
    Connection to server sucessfully 
    Stored string in redis:: Redis 
    Stored string in redis:: Mongodb 
    Stored string in redis:: Mysql
    
    import redis.clients.jedis.Jedis; 
    
    public class RedisKeyJava { 
       public static void main(String[] args) { 
          //Connecting to Redis server on localhost 
          Jedis jedis = new Jedis("localhost"); 
          System.out.println("Connection to server sucessfully"); 
          //store data in redis list 
          // Get the stored data and print it 
          List<String> list = jedis.keys("*"); 
    
          for(int i = 0; i<list.size(); i++) { 
             System.out.println("List of stored keys:: "+list.get(i)); 
          } 
       } 
    }
    

    执行上面代码,将生成以下结果 -

    $javac RedisKeyJava.java 
    $java RedisKeyJava 
    Connection to server sucessfully 
    List of stored keys:: tutorial-name 
    List of stored keys:: tutorial-list
    

    设置redis 服务器连接对象
     /**
      * redisCoonection
      */
     @Bean(name = "shiroConnFactiory")
     public JedisConnectionFactory connectionFactory() {
      JedisConnectionFactory conn = new JedisConnectionFactory();
      conn.setDatabase(redisDatabase);
      conn.setHostName(redisHost);
      conn.setPassword(redisPassword);
      conn.setPort(redisPort);
      conn.setTimeout(redisTimeout);
      return conn;
     }



     /**
      * redisTemplate
      */
     @Bean(name = "redisTemplate")
     public RedisTemplate<byte[], Object> redisTemplate() {
      RedisTemplate<byte[], Object> template = new RedisTemplate<>();
      template.setConnectionFactory(connectionFactory());
      return template;
     }

     /**
      * redisCacheManager
      */
     @Bean(name = "shrioRedisCacheManager")
     @DependsOn(value = "redisTemplate")
     public ShrioRedisCacheManager redisCacheManager() {
      ShrioRedisCacheManager cacheManager = new ShrioRedisCacheManager(redisTemplate());
      return cacheManager;
     }

    /**
     * 项目名:onway
     * 包名:com.pactera.commons.redis
     * 文件名:RedisUtil.java
     * 版本信息:1.0.0
     * 日期:2016年12月7日-下午7:01:40
     * Copyright (c) 2016 Pactera 版权所有
     */
     
    package com.pactera.commons.redis;
    
    import java.io.Serializable;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.stereotype.Component;
    
    /**
     * 类名称:RedisUtil
     * 类描述:redicache 工具类
     * 创建人:lee
     * 创建时间:2016年12月7日 下午7:01:40
     * @version 1.0.0
     */
    @Component
    public class RedisUtil {
        
        @Autowired
        private RedisTemplate redisTemplate;
        
        /**
         * 批量删除对应的value
         * 
         * @param keys
         */
        public void remove(final String... keys) {
            for (String key : keys) {
                remove(key);
            }
        }
        
        /**
         * 批量删除key
         * @param pattern
         */
        public void removePattern(final String pattern) {
            Set<Serializable> keys = redisTemplate.keys(pattern);
            if (keys.size() > 0)
            redisTemplate.delete(keys);
        }
        
        /**
         * 删除对应的value
         * @param key
         */
        public void remove(final String key) {
            if (exists(key)) {
                redisTemplate.delete(key);
            }
        }
        
        /**
         * 判断缓存中是否有对应的value
         * 
         * @param key
         * @return
         */
        public boolean exists(final String key) {
            return redisTemplate.hasKey(key);
        }
        
        /**
         * 读取缓存
         * @param key
         * @return
         */
        public Object get(final String key) {
            Object result = null;
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            result = operations.get(key);
            return result;
        }
        
        /**
         * 写入缓存
         * 
         * @param key
         * @param value
         * @return
         */
        public boolean set(final String key, Object value) {
            boolean result = false;
            try {
                ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
                operations.set(key, value);
                result = true;
            } catch (Exception e) {
            e.printStackTrace();
            }
            return result;
        }
        
        /**
         * 写入缓存
         * @param key
         * @param value
         * @return
         */
        public boolean set(final String key, Object value, Long expireTime) {
            boolean result = false;
            try {
                ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
                operations.set(key, value);
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    }
    /**
     * 项目名:onway
     * 包名:com.pactera.commons.redis
     * 文件名:RedisConfig.java
     * 版本信息:1.0.0
     * 日期:2016年12月7日-下午6:57:43
     * Copyright (c) 2016 Pactera 版权所有
     */
     
    package com.pactera.commons.redis;
    
    import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.cache.CacheManager;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.cache.interceptor.KeyGenerator;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    /**
     * 类名称:RedisConfig
     * 类描述:redis 缓存管理
     * 创建人:lee
     * 创建时间:2016年12月7日 下午6:57:43
     * @version 1.0.0
     */
    @Configuration
    @EnableCaching
    public class RedisConfig extends CachingConfigurerSupport {
        @Bean  
        public KeyGenerator wiselyKeyGenerator(){  
            return new KeyGenerator() {  
                @Override  
                public Object generate(Object target, Method method, Object... params) {  
                    StringBuilder sb = new StringBuilder();  
                    sb.append(target.getClass().getName());  
                    sb.append(method.getName());  
                    for (Object obj : params) {  
                        sb.append(obj.toString());  
                    }  
                    return sb.toString();  
                }  
            };  
      
        }  
      
        @Bean(name = "springCM")
        public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {  
            return new RedisCacheManager(redisTemplate);  
        }  
      
        @Bean  
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {  
            StringRedisTemplate template = new StringRedisTemplate(factory);  
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);  
            ObjectMapper om = new ObjectMapper();  
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
            jackson2JsonRedisSerializer.setObjectMapper(om);  
            template.setValueSerializer(jackson2JsonRedisSerializer);  
            template.afterPropertiesSet();  
            return template;  
        }  
    }
    /**
     * 项目名:onway
     * 包名:com.pactera.commons.redis
     * 文件名:RedisSessionDAO.java
     * 版本信息:1.0.0
     * 日期:2016年11月29日-下午3:11:50
     * Copyright (c) 2016 Pactera 版权所有
     */
    
    package com.pactera.commons.redis;
    
    import java.io.Serializable;
    import java.util.Collection;
    import java.util.HashSet;
    import java.util.Set;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.apache.shiro.session.Session;
    import org.apache.shiro.session.UnknownSessionException;
    import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.data.redis.core.RedisTemplate;
    
    import com.pactera.commons.utils.SerializeUtils;
    
    /**
     * 类名称:RedisSessionDAO 
     * 类描述: 
     * 创建人:heliang 
     * 创建时间:2016年11月29日 下午3:11:50
     * @version 1.0.0
     * @param <V>
     */
    
    public class RedisSessionDAO<V> extends AbstractSessionDAO {
        private Logger logger = LogManager.getLogger(getClass());
        private RedisTemplate<byte[], V> redisTemplate;
    
        public RedisSessionDAO(RedisTemplate<byte[], V> redisTemplate) {
            super();
            this.redisTemplate =  redisTemplate;
        }
    
        @Value("${shiro.expired}")
        private Integer expired = 18000000;
    
    
        public Integer getExpired() {
            return expired;
        }
    
    
        public void setExpired(Integer expired) {
            this.expired = expired;
        }
    
        @Override
        public void update(Session session) throws UnknownSessionException {
            logger.debug("update Session:" + session.getId());
            this.saveSession(session);
    
        }
    
        @SuppressWarnings("unchecked")
        private void saveSession(Session session) {
            if (session == null || session.getId() == null) {
                logger.error("session or session id is null");
                return;
            }
    
            byte[] key = getByteKey(session.getId());
            session.setTimeout(expired);
            logger.debug("Save Session:" + session.getId());
            redisTemplate.opsForValue().set(key, (V) session);
        }
    
        private byte[] getByteKey(Serializable sessionId) {
            if (sessionId instanceof String) {
                String preKey = ShrioRedisCache.prefix + sessionId;
                return preKey.getBytes();
            } else {
                return SerializeUtils.serialize(sessionId);
            }
        }
    
        @Override
        public void delete(Session session) {
            if (session == null || session.getId() == null) {
                logger.error("session or session id is null");
                return;
            }
            logger.debug("delete Session:" + session.getId());
            redisTemplate.delete(getByteKey(session.getId()));
        }
    
        @Override
        public Collection<Session> getActiveSessions() {
            Set<Session> sessions = new HashSet<Session>();
            Set<byte[]> keys = redisTemplate.keys(getByteKey(ShrioRedisCache.prefix + "*"));
            if (keys != null && keys.size() > 0) {
                for (byte[] key : keys) {
                    Session s = (Session) redisTemplate.opsForValue().get(key);
                    sessions.add(s);
                }
            }
    
            return sessions;
        }
    
        @Override
        protected Serializable doCreate(Session session) {
            logger.debug("Session create :" + session.getId());
            Serializable sessionId = this.generateSessionId(session);
            this.assignSessionId(session, sessionId);
            this.saveSession(session);
            return sessionId;
        }
    
        @Override
        protected Session doReadSession(Serializable sessionId) {
            if (sessionId == null) {
                logger.error("session id is null");
                return null;
            }
            logger.debug("Session doReadSession :" + sessionId);
            byte[] key = getByteKey(sessionId);
            Session s = (Session) redisTemplate.opsForValue().get(key);
            return s;
        }
    
    }
    /**
     * 项目名:onway
     * 包名:com.pactera.commons.redis
     * 文件名:ShrioRedisCache.java
     * 版本信息:1.0.0
     * 日期:2016年11月28日-下午3:06:06
     * Copyright (c) 2016 Pactera 版权所有
     */
    
    package com.pactera.commons.redis;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.List;
    import java.util.Set;
    
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.apache.shiro.cache.Cache;
    import org.apache.shiro.cache.CacheException;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    
    import com.google.common.collect.Sets;
    import com.pactera.commons.utils.SerializeUtils;
    
    
    public class ShrioRedisCache<K, V> implements Cache<K, V> {
        private Logger logger = LogManager.getLogger(getClass());
        private RedisTemplate<byte[], V> redisTemplate;
        public static String prefix = "shiro_redis:";
    
        public ShrioRedisCache(RedisTemplate<byte[], V> redisTemplate) {
            this.redisTemplate = redisTemplate;
        }
    
        public ShrioRedisCache(RedisTemplate<byte[], V> redisTemplate, String prefix) {
            this(redisTemplate);
            this.prefix = prefix;
        }
    
        @Override
        public V get(K key) throws CacheException {
            if (logger.isDebugEnabled()) {
                logger.debug("Key: {}", key);
            }
            if (key == null) {
                return null;
            }
    
            byte[] bkey = getByteKey(key);
            return redisTemplate.opsForValue().get(bkey);
        }
    
        @Override
        public V put(K key, V value) throws CacheException {
            if (logger.isDebugEnabled()) {
                logger.debug("Key: {}, value: {}", key, value);
            }
    
            if (key == null || value == null) {
                return null;
            }
    
            byte[] bkey = getByteKey(key);
            redisTemplate.opsForValue().set(bkey, value);
            return value;
        }
    
        @Override
        public V remove(K key) throws CacheException {
            if (logger.isDebugEnabled()) {
                logger.debug("Key: {}", key);
            }
    
            if (key == null) {
                return null;
            }
    
            byte[] bkey = getByteKey(key);
            ValueOperations<byte[], V> vo = redisTemplate.opsForValue();
            V value = vo.get(bkey);
            redisTemplate.delete(bkey);
            return value;
        }
    
        @Override
        public void clear() throws CacheException {
            redisTemplate.getConnectionFactory().getConnection().flushDb();
        }
    
        @Override
        public int size() {
            Long len = redisTemplate.getConnectionFactory().getConnection().dbSize();
            return len.intValue();
        }
    
        @SuppressWarnings("unchecked")
        @Override
        public Set<K> keys() {
            byte[] bkey = (prefix + "*").getBytes();
            Set<byte[]> set = redisTemplate.keys(bkey);
            Set<K> result = Sets.newHashSet();
    
            if (CollectionUtils.isEmpty(set)) {
                return Collections.emptySet();
            }
    
            for (byte[] key : set) {
                result.add((K) key);
            }
            return result;
        }
    
        @Override
        public Collection<V> values() {
            Set<K> keys = keys();
            List<V> values = new ArrayList<>(keys.size());
            for (K k : keys) {
                byte[] bkey = getByteKey(k);
                values.add(redisTemplate.opsForValue().get(bkey));
            }
            return values;
        }
    
        private byte[] getByteKey(K key) {
            if (key instanceof String) {
                String preKey = this.prefix + key;
                return preKey.getBytes();
            } else {
                return SerializeUtils.serialize(key);
            }
        }
    
        public String getPrefix() {
            return prefix;
        }
    
        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }
    }
    /**
     * 项目名:onway
     * 包名:com.pactera.commons.redis
     * 文件名:ShrioRedisCacheManager.java
     * 版本信息:1.0.0
     * 日期:2016年11月28日-下午3:15:04
     * Copyright (c) 2016 Pactera 版权所有
     */
    
    package com.pactera.commons.redis;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.apache.shiro.cache.AbstractCacheManager;
    import org.apache.shiro.cache.Cache;
    import org.apache.shiro.cache.CacheException;
    import org.springframework.data.redis.core.RedisTemplate;
    
    /**
     * 类名称:ShrioRedisCacheManager 
     * 类描述: 
     * 创建人:heliang 
     * 创建时间:2016年11月28日 下午3:15:04
     * 
     * @version 1.0.0
     */
    public class ShrioRedisCacheManager extends AbstractCacheManager {
        private Logger logger = LogManager.getLogger(getClass());
        private RedisTemplate<byte[], Object> redisTemplate;
    
        public ShrioRedisCacheManager(RedisTemplate<byte[], Object> redisTemplate) {
            this.redisTemplate = redisTemplate;
        }
    
        @Override
        protected Cache<byte[], Object> createCache(String name) throws CacheException {
            return new ShrioRedisCache<byte[], Object>(redisTemplate, name);
        }
    
    }










  • 相关阅读:
    efwplus框架
    注册区域
    社招面试记录与总结
    验证码 Captcha 之大插件
    发生内存泄漏?
    Flume+LOG4J+Kafka
    协议如何保证可靠传输
    oracle之spool详细使用总结(转)
    SSH协议详解(转)
    oracle nologging用法(转)
  • 原文地址:https://www.cnblogs.com/jack-Star/p/7263442.html
Copyright © 2011-2022 走看看