zoukankan      html  css  js  c++  java
  • spring-boot集成redis

    application.properties
    #redis 配置
    # Redis数据库索引(默认为0)
    spring.redis.database=0
    # Redis服务器地址
    spring.redis.host=192.168.102.128
    # Redis服务器连接端口
    spring.redis.port=6379
    # Redis服务器连接密码(默认为空)
    spring.redis.password=
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.pool.max-wait=6000
    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.pool.max-active=50
    # 连接池中的最大空闲连接
    spring.redis.pool.max-idle=10
    # 连接池中的最小空闲连接
    spring.redis.pool.min-idle=10
    # 连接超时时间(毫秒)
    spring.redis.timeout=6000

    pom.xml

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <version>1.5.2.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>org.redisson</groupId>
                <artifactId>redisson</artifactId>
                <version>1.0.2</version>
            </dependency>


    RedisConfig.java
    package com.hbd.example.framework.cache.redis;
    
    import org.springframework.beans.factory.annotation.Autowired;
    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.connection.jedis.JedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    import redis.clients.jedis.JedisPoolConfig;
    
    import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;
    
    
    @Configuration
    @EnableCaching
    public class RedisConfig extends CachingConfigurerSupport {
        @Autowired
        private RedisConn redisConn;
    
        /**
         * 生产key的策略
         *
         * @return
         */
    
        @Bean
        @Override
        public KeyGenerator keyGenerator() {
            System.err.println("================>keyGenerator");
            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();
                }
            };
    
        }
    
        /**
         * 管理缓存
         *
         * @param redisTemplate
         * @return
         */
    
        @SuppressWarnings("rawtypes")
        @Bean
        public CacheManager CacheManager(RedisTemplate redisTemplate) {
            System.err.println("================>CacheManager");
            RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    // 设置cache过期时间,时间单位是秒
            rcm.setDefaultExpiration(60);
            Map<String, Long> map = new HashMap<String, Long>();
            map.put("test", 60L);
            rcm.setExpires(map);
            return rcm;
        }
    
        /**
         * redis 数据库连接池
         * @return
         */
        @Bean
        public JedisPoolConfig redisPoolConfig() {
            System.err.println("================>redisPoolConfig");
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            poolConfig.setMaxTotal(redisConn.getMaxActive());
            poolConfig.setMaxIdle(redisConn.getMaxIdle());
            poolConfig.setMinIdle(redisConn.getMinIdle());
            poolConfig.setMaxWaitMillis(redisConn.getMaxWait());
            return poolConfig;
        }
    
    
        @Bean
        public JedisConnectionFactory redisConnectionFactory() {
            System.err.println("================>redisConnectionFactory");
            JedisConnectionFactory factory = new JedisConnectionFactory();
            factory.setHostName(redisConn.getHost());
            factory.setPort(redisConn.getPort());
            factory.setTimeout(redisConn.getTimeout()); // 设置连接超时时间
            factory.setPoolConfig(redisPoolConfig());
            return factory;
        }
    
        /**
         * redisTemplate配置
         *
         * @param factory
         * @return
         */
        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Bean
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
            System.err.println("================>redisTemplate");
            StringRedisSerializer keySerializer = new StringRedisSerializer();
            JdkSerializationRedisSerializer valueSerializer = new JdkSerializationRedisSerializer();
            StringRedisTemplate template = new StringRedisTemplate(factory);
            template.setKeySerializer(keySerializer);
            template.setValueSerializer(valueSerializer);
            template.setConnectionFactory(redisConnectionFactory());
            template.afterPropertiesSet();
            return template;
        }
    
    }

    RedisConn.java

    package com.hbd.example.framework.cache.redis;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties(prefix = "spring.redis")
    public class RedisConn {
        private String host;
        
        private int port;
    
        private int timeout;
    
        @Value("${spring.redis.pool.max-active}")
        private int maxActive;
    
        @Value("${spring.redis.pool.max-idle}")
        private int maxIdle;
    
        @Value("${spring.redis.pool.min-idle}")
        private int minIdle;
    
        @Value("${spring.redis.pool.max-wait}")
        private int maxWait;
    
        public String getHost() {
            return host;
        }
    
        public void setHost(String host) {
            this.host = host;
        }
    
        public int getPort() {
            return port;
        }
    
        public void setPort(int port) {
            this.port = port;
        }
    
        public int getTimeout() {
            return timeout;
        }
    
        public void setTimeout(int timeout) {
            this.timeout = timeout;
        }
    
        public int getMaxActive() {
            return maxActive;
        }
    
        public void setMaxActive(int maxActive) {
            this.maxActive = maxActive;
        }
    
        public int getMaxIdle() {
            return maxIdle;
        }
    
        public void setMaxIdle(int maxIdle) {
            this.maxIdle = maxIdle;
        }
    
        public int getMinIdle() {
            return minIdle;
        }
    
        public void setMinIdle(int minIdle) {
            this.minIdle = minIdle;
        }
    
        public int getMaxWait() {
            return maxWait;
        }
    
        public void setMaxWait(int maxWait) {
            this.maxWait = maxWait;
        }
    }

    RedisUtil.java

    package com.hbd.example.framework.cache.redis;
    
    import org.springframework.dao.DataAccessException;
    import org.springframework.data.redis.connection.RedisConnection;
    import org.springframework.data.redis.core.*;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.Resource;
    import java.io.Serializable;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    
    /**
     * redis cache 工具类
     * 
     */
    
    @Component
    public final class RedisUtil {
    
        @Resource
        private RedisTemplate<Serializable, Object> redisTemplate;
    
        private String redisIp;
    
        /**
         * 批量删除对应的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) {
    //        System.err.println("-----------------------------redisIp"+redisIp);
            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) {
    //        System.err.println("-----------------------------redisIp" + redisIp);
            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) {
    //        System.err.println("-----------------------------redisIp"+redisIp);
            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;
        }
    
        public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
            this.redisTemplate = redisTemplate;
        }
    
        public String getRedisIp() {
            return redisIp;
        }
    
        public void setRedisIp(String redisIp) {
            this.redisIp = redisIp;
        }
    
    
        /**
         * 设置新值,同时返回旧值
         * @param lockKey
         * @param stringOfLockExpireTime
         * @return
         */
        public String getSet(final String lockKey, final String stringOfLockExpireTime) {
            String result = redisTemplate.execute(new RedisCallback<String>() {
                @Override
                public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
                    byte[] bytes = redisConnection.getSet(lockKey.getBytes(), stringOfLockExpireTime.getBytes());
                    if(bytes != null) {
                        return new String(bytes);
                    }
                    return null;
                }
            });
            return result;
        }
    
        /**
         * 如果不存在key则插入
         * @param lockKey
         * @param stringOfLockExpireTime
         * @return true 插入成功, false 插入失败
         */
        public boolean setnx(final String lockKey, final String stringOfLockExpireTime) {
            return redisTemplate.execute(new RedisCallback<Boolean>() {
                @Override
                public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
                    return redisConnection.setNX(lockKey.getBytes(), stringOfLockExpireTime.getBytes());
                }
            });
        }
    
        /**
         * setnx 和 getSet方式插入的数据,调用此方法获取
         * @param key
         * @return
         */
        public String getInExecute(final String key) {
            String result = redisTemplate.execute(new RedisCallback<String>() {
                @Override
                public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
                    byte[] bytes = redisConnection.get(key.getBytes());
                    if (bytes == null) {
                        return null;
                    } else {
                        return new String(bytes);
                    }
                }
            });
            return result;
        }
    
        /**
         * 将缓存保存在map集合中
         * @param redisKey
         * @param mapKey
         * @param mapValue
         * @return
         */
        public boolean putInMap(final String redisKey, String mapKey, Object mapValue) {
            boolean result = false;
            try {
                HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
                operations.put(redisKey, mapKey, mapValue);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    
        public Object getOneFromMap(final String redisKey, String mapKey) {
            HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
            return operations.get(redisKey, mapKey);
        }
    
        public Object getAllFromMap(final String redisKey) {
            HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
            return operations.values(redisKey);
        }
    
        public void removeFromMap(final String redisKey, Object obj) {
            HashOperations<Serializable, Object, Object> operations = redisTemplate.opsForHash();
            operations.delete(redisKey, obj);
        }
    
        public boolean setList(final String key, Object value) {
            boolean result = false;
            try {
                ListOperations<Serializable, Object> listOperations = redisTemplate.opsForList();
                listOperations.leftPush(key, value);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    
        public Object getList(final String key) {
            ListOperations<Serializable, Object> listOperations = redisTemplate.opsForList();
            return listOperations.range(key,0,listOperations.size(key));
        }
    
    }

    OrgController.java

    package com.hbd.example.org.controller;
    
    import com.hbd.example.framework.cache.redis.RedisUtil;
    import com.hbd.example.framework.exception.runtime.ServiceException;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    @RestController
    @RequestMapping("/org")
    public class OrgController {
    
        @Resource
        RedisUtil redisUtil;
    
        @RequestMapping("/set")
        public String set(@RequestParam String key, @RequestParam String value) {
            redisUtil.set(key,value);
            return "success";
        }
    
        @RequestMapping("/get")
        public String get(String key) {
            Object o = redisUtil.get(key);
            System.out.println(o);
            return "redis value :"+o;
        }
    
    }
  • 相关阅读:
    PHP 大小写转换、首字母大写、每个单词首字母大写转换相关函数
    【论文学习4】BiSample: Bidirectional Sampling for Handling Missing Data with Local Differential Privacy
    【论文学习3】Local Differential Privacy for Deep Learning
    【论文学习2】 Differential Privacy Reinforcement Learning
    深度学习中的优化算法
    Spatial crowdsourcing
    “pip install tensorflow ”出现错误
    python或pip'不是内部或外部命令”
    pip install torch出现错误
    打不开gitHub的解决方法
  • 原文地址:https://www.cnblogs.com/cocoat/p/7614971.html
Copyright © 2011-2022 走看看