zoukankan      html  css  js  c++  java
  • SpringBoot+Redis整合

    SpringBoot+Redis整合

    1.在pom.xml添加Redis依赖

            <!--整合Redis-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.9.0</version>
            </dependency>
            <!--整合Redis-->
    

    2.在application.yml配置Redis

    #引入Redis 安装在Linux
    jedis :
      pool :
        host : 192.168.13.128
        port : 6379
        password: 123456
        timeout: 10000
        config :
          maxTotal: 100
          maxIdle: 10
          maxWaitMillis : 100000
    

      

    3.在Resources添加redis.properties

    #redis配置开始
    # Redis数据库索引(默认为0)
    spring.redis.database=0
    # Redis服务器地址
    spring.redis.host=192.168.13.128
    # Redis服务器连接端口
    spring.redis.port=6379
    # Redis服务器连接密码(默认为空)
    spring.redis.password=123456
    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.jedis.pool.max-active=1024
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.jedis.pool.max-wait=10000
    # 连接池中的最大空闲连接
    spring.redis.jedis.pool.max-idle=200
    # 连接池中的最小空闲连接
    spring.redis.jedis.pool.min-idle=0
    # 连接超时时间(毫秒)
    spring.redis.timeout=10000
    #redis配置结束
    spring.redis.block-when-exhausted=true
    

      

    4.配置RedisConfiguration.java类,自动注入

    @Configuration
    @PropertySource("classpath:redis.properties")
    public class RedisConfiguration {
    
        @Value("${spring.redis.host}")
        private String host;
    
        @Value("${spring.redis.port}")
        private int port;
    
        @Value("${spring.redis.timeout}")
        private int timeout;
    
        @Value("${spring.redis.jedis.pool.max-idle}")
        private int maxIdle;
    
        @Value("${spring.redis.jedis.pool.max-wait}")
        private long maxWaitMillis;
    
        @Value("${spring.redis.password}")
        private String password;
    
        @Value("${spring.redis.block-when-exhausted}")
        private boolean  blockWhenExhausted;
    
        @Bean
        public JedisPool redisPoolFactory()  throws Exception{
            System.out.println("JedisPool注入成功!!");
            System.out.println("redis地址:" + host + ":" + port);
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxIdle(maxIdle);
            jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
            // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
            jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
            // 是否启用pool的jmx管理功能, 默认true
            jedisPoolConfig.setJmxEnabled(true);
            JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
            return jedisPool;
        }
    
    }
    View Code

    5.配置Util类:序列化类SerializeUtil,参数静态类RedisConstants,Redis基础操作类RedisUtil

    public class SerializeUtil {
    
    
    
        public static byte[] serialize(Object object) {
            ObjectOutputStream oos = null;
            ByteArrayOutputStream baos = null;
            try {
    //序列化
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(object);
                byte[] bytes = baos.toByteArray();
                return bytes;
            } catch (Exception e) {
            }
            return null;
        }
    
        public static Object unserialize(byte[] bytes) {
            ByteArrayInputStream bais = null;
            try {
    //反序列化
                bais = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bais);
                return ois.readObject();
            } catch (Exception e) {
            }
            return null;
        }
    
    
        /**
         * 序列化 list 集合
         *
         * @param list
         * @return
         */
        public static byte[] serializeList(List<?> list) throws Exception {
            if (list == null || list.size() == 0) {
                return null;
            }
            ObjectOutputStream oos = null;
            ByteArrayOutputStream baos = null;
            byte[] bytes = null;
            try {
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                for (Object obj : list) {
                    oos.writeObject(obj);
                }
                bytes = baos.toByteArray();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                close(oos);
                close(baos);
            }
            return bytes;
        }
    
        /**
         * 反序列化 list 集合
         *
         * @param
         * @return
         */
        public static List<?> unserializeList(byte[] bytes) throws Exception {
            if (bytes == null) {
                return null;
            }
            List<Object> list = new ArrayList<Object>();
            ByteArrayInputStream bais = null;
            ObjectInputStream ois = null;
            try {
                // 反序列化
                bais = new ByteArrayInputStream(bytes);
                ois = new ObjectInputStream(bais);
                while (bais.available() > 0) {
                    Object obj = (Object) ois.readObject();
                    if (obj == null) {
                        break;
                    }
                    list.add(obj);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                close(bais);
                close(ois);
            }
            return list;
        }
    
    
    }
    View Code
    public class RedisConstants {
    
        public static final String spilt=":";
    
        /**
         * redis库0  保存档案树
         */
        public static final Integer datebase0=0;
    
    
        /**
         * redis库1  保存档案树
         */
        public static final Integer datebase1=1;
    
        /**
         * 1.redis库2 保存档案表格
         * 2.保存分页码
         */
        public static final Integer datebase2=2;
    
        /**
         * redis库3 保存档案image url
         */
        public static final Integer datebase3=3;
    
        /**
         * 1.redis库4 保存手机验证码
         *
         */
        public static final Integer datebase4=4;
    
        /**
         * redis库5 保存身份认证信息
         */
        public static final Integer datebase5=5;
    
        /**
         * redis库6 记录身份认证次数
         */
        public static final Integer datebase6=6;
    
        /**
         * redis库7 记录重发次数
         */
        public static final Integer datebase7=7;
    
        /**
         * redis库8 记录任务参数
         */
        public static final Integer datebase8=8;
    
    
        public RedisConstants() {
    
        }
    
    }
    View Code
    @Component
    //@Slf4j
    public class RedisUtil {
    
        private static  final Log log= LogFactory.getLog(RedisUtil.class);
    
        @Autowired
        private JedisPool jedisPool;
    
        public RedisUtil() {
        }
    
        /**
         * <p>
         * 通过key获取储存在redis中的value
         * </p>
         * <p>
         * 并释放连接
         * </p>
         *
         * @param key
         * @param indexdb 选择redis库 0-15
         * @return 成功返回value 失败返回null
         */
        public String get(String key,int indexdb) {
            Jedis jedis = null;
            String value = null;
            try {
                jedis = jedisPool.getResource();
                jedis.select(indexdb);
                value = jedis.get(key);
                System.out.println(value);
              //  log.info(value);
            } catch (Exception e) {
    
             log.error(e.getMessage());
            } finally {
                returnResource(jedisPool, jedis);
            }
            return value;
        }
    
        /**
         * <p>
         * 通过key获取储存在redis中的value
         * </p>
         * <p>
         * 并释放连接
         * </p>
         *
         * @param key
         * @param indexdb 选择redis库 0-15
         * @return 成功返回value 失败返回null
         */
        public byte[] get(byte[] key,int indexdb) {
            Jedis jedis = null;
            byte[] value = null;
            try {
                jedis = jedisPool.getResource();
                jedis.select(indexdb);
                value = jedis.get(key);
            } catch (Exception e) {
    
                log.error(e.getMessage());
            } finally {
                returnResource(jedisPool, jedis);
            }
            return value;
        }
    }
    View Code

    6.在Controller添加操作类RedisController

    @Controller
    @RequestMapping(value="/redis")
    public class RedisController{
    
        @Autowired
        RedisUtil redisUtil;
    
        @Autowired
        AccountService accountService;
    
        @RequestMapping(value = "getRedis",method = RequestMethod.POST)
        @ResponseBody
        public ModelMap getRedis() throws Exception {
    
            //存储String
    //        redisUtil.set("20182019","这是一条测试数据1", RedisConstants.datebase1);
    //        Long resExpire = redisUtil.expire("20182018", 60, RedisConstants.datebase1);//设置key过期时间
    //        String res = redisUtil.get("20182019", RedisConstants.datebase1);
    //        String name = redisUtil.get("name", RedisConstants.datebase0);
    
    //        //存储hash-map
    //        Map<String, String> map=new HashMap<String,String>();
    //        map.put("a","a1");
    //        map.put("b","a2");
    //        map.put("c","a2");
    //        redisUtil.hmset("dd",map,RedisConstants.datebase1);
    
    //        List<String> list111 = (List<String>) redisUtil.getList("testlist");
    //        System.out.println(list111);
    
            //存储list serialize
    //       List<UserVO>  userList=accountService.selsetUserList();
    //       System.out.println(userList);
    //       for(UserVO user:userList){
    //           redisUtil.lpush(RedisConstants.datebase1,"userList",user.getUserid()+"");
    //           redisUtil.hset("user:"+user.getUserid(),"userId",user.getUserid()+"");
    //           redisUtil.hset("user:"+user.getUsername(),"userName",user.getUsername()+"");
    //           redisUtil.hset("user:"+user.getEmail(),"usereEail",user.getEmail()+"");
    //
    //       }
    
            //获取List数据
          String userId=  redisUtil.hget("userList:"+1,"userId");
          String userName=  redisUtil.hget("userList:"+1,"userName");
          String userEmail=  redisUtil.hget("userList:"+1,"userEmail");
            System.out.println(userId);
            System.out.println(userName);
            System.out.println(userEmail);
    
            return null;
    
        }
    
    
    
    
    }
    View Code

      

  • 相关阅读:
    Swift的函数与函数指针、闭包Closure等相关内容介绍
    spring+dubbo整合
    常用设计模式-适配器模式
    常用设计模式-工厂模式
    java动态代理
    程序对关系型数据库批量操作
    springboot整合mybatis
    JAVA代码实现多级树结构封装对象
    springboot集成redis缓存
    springboot入门
  • 原文地址:https://www.cnblogs.com/ningshare/p/10711436.html
Copyright © 2011-2022 走看看