• 【SpringBoot | Redis】SpringBoot整合Redis


    SpringBoot整合Redis

    1. pom.xml中引入Redis相关包

    请注意,这里我们排除了lettuce驱动,采用了jedis驱动

    <!-- redis的依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <!-- 不依赖Redis的异步客户端lettuce -->
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 引入Redis的客户端驱动 Jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
    

    2. application.yml中配置Redis

    这里给出的是部分配置,更多的配置可百度相关文档

    spring:
      redis:
        database: 1 # Redis数据库编号,这里采用了1号数据库
        host: 127.0.0.1 # 主机号
        port: 6379 # 端口号
        timeout: 10000 # 链接超时时间
        # jedis配置
        jedis: 
          pool:
            max-idle: 20
            min-idle: 5
            max-active: -1
            max-wait: -1
    
    

    3. 初始化RedisTemplate

    我将其放在com.xxx.xxx.config包下,统一配置文件存放路径。
    这里序列化都采用StringRedisSerializer,可根据需求改写为Jackson2JsonRedisSerializer序列化器

    package com.xxx.xxx.config;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    /**
     * redis配置类
     *
     * @author axiang 
     */
    @Configuration
    public class RedisConfig {
        /**
         * 初始化RedisTemplate
         *
         * @param factory
         * @return
         */
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
            template.setConnectionFactory(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);
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            // key采用String的序列化方式
            template.setKeySerializer(stringRedisSerializer);
            // hash的key也采用String的序列化方式
            template.setHashKeySerializer(stringRedisSerializer);
            // value序列化方式采用String
            template.setValueSerializer(stringRedisSerializer);
            // hash的value序列化方式采用 String
            template.setHashValueSerializer(stringRedisSerializer);
    
    //      // value序列化方式采用jackson
    //      template.setValueSerializer(jackson2JsonRedisSerializer);
    //      // hash的value序列化方式采用jackson
    //      template.setHashValueSerializer(jackson2JsonRedisSerializer);
    
            template.afterPropertiesSet();
            return template;
    
        }
    }
    
    
    

    4. 编写RedisUtils,二次封装RedisTemplate

    根据业务需要,二次封装Redis模板类,方便直接调用。同时使用@Component注解将工具类注册为bean,交由spring容器管理

    package com.xxx.xxx.component.redis;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    import org.springframework.util.CollectionUtils;
    import org.springframework.util.StringUtils;
    
    import java.util.concurrent.TimeUnit;
    
    /**
     * Redis配置类
     *
     * @author axiang
     */
    @Component
    public class RedisUtils {
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        /**
         * 指定缓存失效时间
         *
         * @param key
         * @param time
         * @return
         */
        public boolean expire(String key, long time) {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
                return true;
            } else {
                return false;
            }
    
        }
    
        /**
         * 根据key 获取过期时间
         *
         * @param key
         * @return 时间(秒)
         */
        public long getExpire(String key) {
            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        }
    
        /**
         * 判断key是否存在
         *
         * @param key 键
         * @return true 存在 false不存在
         */
        public boolean hasKey(String key) {
            return redisTemplate.hasKey(key);
        }
    
        /**
         * 删除缓存
         *
         * @param key 可以传一个值 或多个
         */
        public void del(String... key) {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    redisTemplate.delete(key[0]);
                } else {
                    redisTemplate.delete(CollectionUtils.arrayToList(key));
                }
            }
        }
    
        /*============================String=============================*/
    
        /**
         * 普通缓存获取
         *
         * @param key 键
         * @return 值
         */
    
        public Object get(String key) {
            return StringUtils.isEmpty(key) ? null : redisTemplate.opsForValue().get(key);
        }
    
        /**
         * 普通缓存放入
         *
         * @param key   键
         * @param value 值
         * @return true成功 false失败
         */
        public boolean set(String key, Object value) {
            redisTemplate.opsForValue().set(key, value);
            return true;
        }
    
        /**
         * 普通缓存放入并设置时间
         *
         * @param key   键
         * @param value 值
         * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
         * @return true成功 false 失败
         */
        public boolean set(String key, Object value, long time) {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        }
    
    
    }
    
    

    5. 调用并测试功能

    这里展示的代码为使用redis进行鉴权的操作类,仅展示Redis操作相关内容,鉴权实现请查看本博客其他内容

    package com.xxx.xxx.component.redis;
    
    import com.xxx.xxx.component.token.TokenManager;
    import com.xxx.xxx.component.token.TokenModel;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.util.StringUtils;
    
    /**
     * token 在 redis 上的操作类,封装了对Redis的一些操作
     *
     * @author axiang 
     */
    @Component
    public class RedisTokenManager implements TokenManager {
    
        @Autowired
        RedisUtils redisUtils;
    
        /**
         *
         * @param username
         * @return
         */
        @Override
        public TokenModel createToken(String username) {
            String token = "xxx";
            redisUtils.set(username, token);
            return new TokenModel(username, token);
        }
    
    
        @Override
        public boolean checkToken(TokenModel model) {
            if (null == model) {
                return false;
            }
            String token;
            token = (String) redisUtils.get(model.getUsername());
            if (StringUtils.isEmpty(token) || !token.equals(model.getToken())) {
                return false;
            }
            // 如果鉴权成功,延长过期时间
            // redis.boundValueOps(model.getUsername()).expire();
            return true;
        }
    
        @Override
        public String createAuth(TokenModel model) {
            String username = model.getUsername();
            String token = model.getToken();
            String auth = username + "_" + token;
            return auth;
    
        }
    
        @Override
        public TokenModel getToken(String authentication) {
            if (StringUtils.isEmpty(authentication)) {
                return null;
            }
            String[] param = authentication.split("_");
            int paramLength = 2;
            if (paramLength != param.length) {
                return null;
            }
            return new TokenModel(param[0], param[1]);
        }
    
        @Override
        public void deleteToken(String username) {
            redisUtils.del(username);
        }
    }
    
    
  • 相关阅读:
    马的遍历 new
    锤子剪刀布 new
    npm 打包 new
    Linux 锁机制
    ubuntu virtualbox 下安装xp,识别usb
    ubuntu设置快捷键
    linux神奇的系统请求系统救命草
    linux 内核动态内存分配测试(纯属娱乐哈)
    C之绝妙(一道很NB的面试题)
    虚拟机virtualbox:Could not find an open hard disk with UUID {368441269e88468698582d1a0568f53c}.
  • 原文地址:https://www.cnblogs.com/axiangcoding/p/11913192.html
Copyright © 2020-2023  润新知