美文网首页
springboot整合redis

springboot整合redis

作者: 拼搏男孩 | 来源:发表于2020-04-25 10:22 被阅读0次

    1、添加依赖

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.6.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.qianfeng</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>demo</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.2</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-json</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.16</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    相比以前这次就多了两个依赖redis和json的依赖,json的依赖用来序列化与反序列化Java对象。

    2、编写配置类

    RedeisConfig.java

    package com.qianfeng.config;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.cache.CacheManager;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.cache.interceptor.KeyGenerator;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.cache.RedisCacheWriter;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
    import org.springframework.data.redis.core.RedisOperations;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    import java.lang.reflect.Method;
    
    @Configuration
    @ConditionalOnClass(RedisOperations.class)
    @EnableConfigurationProperties(RedisProperties.class)
    public class RedisConfig extends CachingConfigurerSupport {
        /**
         * 自定义缓存Key的生成策略,默认的生成策略是乱码,通过spring的依赖注入特性进行自定义的配置注入
         * @return keyGenerator key的生成器
         */
        @Bean
        @Override
        public KeyGenerator keyGenerator() {
            return new KeyGenerator() {
                @Override
                public Object generate(Object o, Method method, Object... objects) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(o.getClass().getName());
                    sb.append(method.getName());
                    for (Object object : objects) {
                        sb.append(object.toString());
                    }
                    return sb.toString();
                }
            };
        }
    
        /**
         * 混村配置管理器
         * @param factory
         * @return
         */
        @Bean
        public CacheManager cacheManager(LettuceConnectionFactory factory){
            //以锁写入的方式创建RedisCacheWriter
            RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);
            //创建默认缓存配置对象
            RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
            RedisCacheManager cacheManager = new RedisCacheManager(writer,config);
            return cacheManager;
        }
        @Bean
        @ConditionalOnMissingBean(name = "redisTemplate")
        public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory factory){
            RedisTemplate<String,Object> template = new RedisTemplate<>();
            template.setConnectionFactory(factory);
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            //使用jackson实现对于对象的序列化
            Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
            serializer.setObjectMapper(om);
            //设置键的序列化方式
            template.setKeySerializer(new StringRedisSerializer());
            //设置值的序列化方式
            template.setValueSerializer(serializer);
            //设置hash类型的key的序列化方式
            template.setHashKeySerializer(new StringRedisSerializer());
            //设置hash类型的value的序列化方式
            template.setHashValueSerializer(serializer);
            return template;
        }
    
        public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory){
            StringRedisTemplate template = new StringRedisTemplate();
            template.setConnectionFactory(factory);
            return template;
        }
    }
    

    3、编写工具类

    RedisUtil

    package com.qianfeng.util;
    
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.stereotype.Component;
    import org.springframework.util.CollectionUtils;
    
    import javax.annotation.Resource;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    @Component
    public class RedisUtil {
        @Resource
        private RedisTemplate<String,Object> redisTemplate;
    
        @Resource
        private StringRedisTemplate stringRedisTemplate;
        /**
         * 设置缓存的失效时间
         * @param key
         * @param time
         * @return
         */
        public boolean expire(String key,long time){
            try {
                if(time>0){
                    redisTemplate.expire(key,time, TimeUnit.SECONDS);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 根据key拿到缓存的失效时间
         * @param key
         * @return
         */
        public long getExpire(String key){
            return redisTemplate.getExpire(key,TimeUnit.SECONDS);
        }
    
        /**
         * 判断缓存中是否有key
         * @param key
         * @return
         */
        public boolean hasKey(String key){
            return redisTemplate.hasKey(key);
        }
    
        /**
         * 根据键删除值
         * @param keys
         */
        public void delete(String ... keys){
            if(keys!=null && keys.length>0){
                if(keys.length == 1){
                    redisTemplate.delete(keys[0]);
                }
                else {
                    redisTemplate.delete(CollectionUtils.arrayToList(keys));
                }
            }
        }
    
        /**
         * 获取string类型的key对应的值
         * @param key
         * @return
         */
        public Object get(String key){
            return key == null ? null:redisTemplate.opsForValue().get(key);
        }
    
    
        /**
         * 设置String类型的key的Object类型的value
         * @param key
         * @param value
         * @return
         */
        public boolean set(String key,Object value){
            try {
                redisTemplate.opsForValue().set(key,value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 设置String类型的key的Object类型的value,并设置有效时间
         * @param key
         * @param value
         * @param time
         * @return
         */
        public boolean set(String key,Object value,long time){
            try {
                if(time>0){
                    redisTemplate.opsForValue().set(key, value, time,TimeUnit.SECONDS);
                }
                else{
                    set(key, value);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 设置value为hash类型的键值对
         * @param key
         * @param map
         * @return
         */
        public boolean hmset(String key, Map<String,Object> map){
            try {
                redisTemplate.opsForHash().putAll(key,map);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 也是设置value为hash类型的键值对,只不过只有一对键值对
         * @param key
         * @param field
         * @param value
         * @return
         */
        public boolean hset(String key,String field,Object value){
            try {
                redisTemplate.opsForHash().put(key,field,value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 设置hash类型的存储并设置失效时间
         * @param key
         * @param map
         * @param time
         * @return
         */
        public boolean hmset(String key, Map<String,Object> map,long time){
            try {
                redisTemplate.opsForHash().putAll(key,map);
                if(time>0){
                    expire(key,time);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 设置hash中指定key下的field的值为value,并设置失效时间
         * @param key
         * @param field
         * @param value
         * @param time
         * @return
         */
        public boolean hset(String key,String field,Object value,long time){
            try {
                redisTemplate.opsForHash().put(key,field,value);
                if(time>0){
                    expire(key,time);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 通过key与field获得value
         * @param key
         * @param field
         * @return
         */
        public Object hget(String key,String field){
            return redisTemplate.opsForHash().get(key,field);
        }
    
        /**
         * 通过key获取hash
         * @param key
         * @return
         */
        public Map<Object,Object> hmget(String key){
            return redisTemplate.opsForHash().entries(key);
        }
    }
    

    4、编写测试类

    package com.qianfeng;
    
    import com.qianfeng.entity.Users;
    import com.qianfeng.service.IUserService;
    import com.qianfeng.util.RedisUtil;
    import org.junit.jupiter.api.Test;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import javax.annotation.Resource;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    @SpringBootTest
    public class RedisTest {
        @Resource
        private RedisUtil redisUtil;
        @Resource
        private IUserService userService;
        @Test
        public void stringTest() throws InterruptedException{
            System.out.println(redisUtil.set("hello", "world"));
            System.out.println(redisUtil.get("hello"));
            System.out.println(redisUtil.set("hello", "tom",2));
            Thread.sleep(2000);
            System.out.println(redisUtil.get("hello"));
        }
        @Test
        public void stringTest2 (){
            Users users = new Users(1,"张三","zhangsan123",23,1,"浙江省杭州市");
            System.out.println(redisUtil.set("user1", users));
            System.out.println(redisUtil.get("user1"));
        }
        @Test
        public void stringTest3(){
            List<Users> users = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                users.add(new Users(i,"user"+i,"user"+i,20+i,1,"湖北省武汉市"));
            }
            System.out.println(redisUtil.set("names",users));
            Object obj = redisUtil.get("names");
            System.out.println(obj);
        }
        @Test
        public void stringTest4(){
            Map<String,String> map = new HashMap<>();
            map.put("zhangsan","wuhan");
            map.put("lisi","guangzhou");
            System.out.println(redisUtil.set("boys",map));
            System.out.println(redisUtil.get("boys"));
        }
        @Test
        public void hashTest(){
            Map<String,Object> map = new HashMap<>();
            map.put("zhangsan",new Users(1,"zhangsan","zhansan123",22,1,"广东省深圳市"));
            System.out.println(redisUtil.hmset("xiyouji", map));
            System.out.println(redisUtil.hmget("xiyouji"));
        }
        @Test
        public void databaseTest() throws InterruptedException{
            List<Users> list = userService.getAllUsers();
            for (Users users : list) {
                redisUtil.set("user"+users.getId(),users);
            }
            Thread.sleep(5);
            int userId = 1;
            String key = "user"+userId;
            Users user = (Users) redisUtil.get(key);
            if(user == null){
                Users user1 = userService.getUserById(userId);
                if(user1==null){
                    System.out.println("你所查找的用户不存在");
                }
                else {
                    redisUtil.set("user"+userId,user1);
                    System.out.println(user1);
                }
            }
            else {
                System.out.println(user);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:springboot整合redis

          本文链接:https://www.haomeiwen.com/subject/fdyhwhtx.html