美文网首页IT@程序员猿媛SpringBoot精选简友广场
SpringBoot初次集成Redis踩坑,安装+使用

SpringBoot初次集成Redis踩坑,安装+使用

作者: 程就人生 | 来源:发表于2019-11-05 21:20 被阅读0次
    图片来自网络

    很多开发者都知道,Redis(Remote Dictionary Server 远程字典服务)是一款基于key、value的存储系统,既可以基于内存做缓存,也可以像数据库一样进行数据的持久化,是用C语言开发的,性能上不用说。接下来,就在win10上安装Redis,并整合springboot来看一下是如何使用的吧。

    第一部分,win10下Redis的安装;

    首先,下载Redis压缩包,根据系统是64位的还是32位的,下载对应版本的压缩包,这里下载64位的,下载地址:https://github.com/MicrosoftArchive/redis/releases,下载后进行解压;

    下载地址

    第二步,安装;使用管理员身份打开cmd命令窗口,进入到解压目录下,使用命令进行Redis的安装和注册;
    安装命令

    redis-server.exe --service-install redis.windows.conf --loglevel verbose
    
    安装成功示意图

    启动服务命令

    redis-server.exe  --service-start
    
    启动成功示意图

    关闭服务命令

    redis-server.exe  --service-stop
    

    第三步,指令操作;安装成功后,就可以使用指令操作Redis了,Redis中的命令不分大小写,这点需要注意;
    Redis查看配置相关命令:

    #查看端口号
    config get port
    #查看ip地址
    config get bind
    #连接超时时间
    config get timeout
    #设置为900秒内有1个更改,300秒内有10个更改,60秒内有10000个更改,三个条件满足一个,就同步更新到文件;
    config set save "900 1 300 10 60 10000"
    ......
    

    Redis客户端相关命令

    #连接Redis的命令格式,没有密码时,可以省略-a
    redis-cli -h 127.0.0.1 -p 6379 -a "123456"
    #设置key,value
    set key value
    #获取key的value
    get key
    #是否存在key,存在是返回1,否则返回0
    exists key
    #查看key的过期时间
    expire key
    #返回key的过期时间,-1为永不过期
    ttl key
    #删除key,返回删除的影响个数
    del key
    

    Redis所支持的数据类型:String字符串类型、Hash哈希类型、List列表类型、Set集合类型、Zset有序集合类型。

    第二部分,springboot整合Redis
    首先,在pom文件中引入springboot集成redis的架包;这里springboot依旧使用2.1.4版本;

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>   
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
    

    第二步,redisconfig的配置文件;在这里,实体使用java.io.serializable进行序列化,也可以在配置文件中自定义序列化规则;

    import java.time.Duration;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.cache.annotation.EnableCaching;
    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.connection.RedisConnectionFactory;
    import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
    import org.springframework.data.redis.core.RedisOperations;
    import org.springframework.data.redis.core.RedisTemplate;
    
    /**
     * redis缓存配置文件
     * @author 程就人生
     * @date 2019年11月5日
     */
    @Configuration
    @ConditionalOnClass(RedisOperations.class) // 系统中有RedisOperations类时
    @EnableConfigurationProperties(RedisProperties.class) // 启动RedisProperties这个类
    @EnableCaching //启动缓存机制
    public class RedisConfig extends CachingConfigurerSupport {
    
        @SuppressWarnings("rawtypes")
        @Autowired
        private RedisTemplate redisTemplate;
    
        /**
         * 配置缓存管理器
         * @param connectionFactory
         * @return
         *
         */
        @Bean
        public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
            
            LettuceConnectionFactory jedisConnection = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
            // 指定dbindex,默认0
            jedisConnection.setDatabase(2); 
            
            redisTemplate.setConnectionFactory(jedisConnection);
            
            jedisConnection.resetConnection();
    
            RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                                                                     // 20分钟缓存失效
                                                                    .entryTtl(Duration.ofSeconds(60 * 20))
                                                                    // 不缓存null值
                                                                    .disableCachingNullValues();
            RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
                                                                   .cacheDefaults(config)
                                                                   .transactionAware()
                                                                   .build();
            
            return redisCacheManager;
        }
    }
    

    第三步,properties中对redis的属性配置

    #Redis
    # 缓存时长,单位秒
    cache.default-exp=72
    spring.redis.database=0
    spring.redis.host=127.0.0.1
    spring.redis.port=6379
    # 密码
    spring.redis.password=
    # 连接超时时间 单位 ms(毫秒)
    spring.redis.timeout=3000
    # 连接池中的最大空闲连接,默认值也是8
    spring.redis.lettuce.pool.max-idle=100
    # 连接池中的最小空闲连接,默认值也是0
    spring.redis.lettuce.pool.min-idle=50
    # 如果赋值为-1,则表示不限制
    spring.redis.lettuce.pool.max-wait=2000
    

    第四步,service层对redis的操作,还有其他的类一起上了;
    实体类,需要序列号:

    import java.io.Serializable;
    /**
     * 继承java.io.Serializable进行序列号处理
     * @author 程就人生
     * @date 2019年11月5日
     */
    public class Test implements Serializable{
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        private String uid;
        
        private String username;
        
        private String password;
        
        private String sex;
    
        public String getUid() {
            return uid;
        }
    
        public void setUid(String uid) {
            this.uid = uid;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        @Override
        public String toString() {
            return "Test [uid=" + uid + ", username=" + username + ", password=" + password + ", sex=" + sex + "]";
        }
    }
    

    service服务类,redis增删改查的实现:

    import com.example.demo.entity.Test;
    public interface TestService {
        public Test add(Test test);
        
        public Test update(Test test);
        
        public Test del(String uid);
        
        public Test retrieve(String uid);
        
    }
    
    import com.example.demo.entity.Test;
    import com.example.demo.service.TestService;
    /**
     * redis缓存操作示例CRUD
     * @author 程就人生
     * @date 2019年11月5日
     */
    @Service
    @CacheConfig(cacheNames = "testCache")
    public class TestServiceImpl implements TestService {
    
        public static final String USER_UID_PREFIX = "'testCache:'+";
    
        /**
         * CRUD 之  新增
         * @param Test test  在redis客户端,以get testCache::testCache:123进行查看所存储的值
         */
        @CachePut(key = USER_UID_PREFIX + "T(String).valueOf(#test.uid)")
        @Override
        public Test add(final Test test) {
            //保存到数据库
            return test;
        }
    
        /**
         * 带条件的修改缓存
         * @param Test test
         * @return Test
         */
        @CachePut(key = "T(String).valueOf(#user.uid)", condition = "#test.uid>1000")
        public Test cacheUserWithCondition(final Test test) {
            //保存到数据库
            //返回值,将保存到缓存
            return test;
        }
    
    
        /**
         * CRUD 之   查询,unless="#result == null",不存在时返回null,没有这一句会报错
         * @param uid
         * @return test
         */
        @Cacheable(key = USER_UID_PREFIX + "T(String).valueOf(#uid)",unless="#result == null")
        @Override
        public Test retrieve(String uid) {
            //如果缓存没有,则从数据库中加载,有则返回查询结果
            return null;
        }
    
        /**
         * CRUD 之 删除
         * @param uid
         */
    
        @CacheEvict(key = USER_UID_PREFIX + "T(String).valueOf(#uid)")
        @Override
        public Test del(String uid) {
    
            //从缓存数据库中删除
            return null;
        }
    
        /**
         * 删除userCache中的全部缓存
         */
        @CacheEvict(value = "testCache", allEntries = true)
        public void deleteAll() {
    
        }
    
        /**
         * 根据uid进行修改
         */
        @CachePut(key = USER_UID_PREFIX + "T(String).valueOf(#test.uid)")
        @Override
        public Test update(Test test) {
            //保存到数据库
            return test;
        }
    }
    

    控制层,调用service,进行redis的增删改查:

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.example.demo.entity.Test;
    import com.example.demo.service.TestService;
    
    /**
     * 调用service进行redis的CRUD
     * @author 程就人生
     * @date 2019年11月5日
     */
    @RestController
    public class TestController {
        
        @Autowired
        private TestService testService;
    
        //新增
        @GetMapping("/add")
        public Test add(){
            Test test = new Test();
            test.setUid("123");
            test.setUsername("aa");
            testService.add(test);
            System.out.println("新增操作:"+test.toString());
            return test;
        }
        
        //删除
        @GetMapping("/del")
        public void del(){      
            testService.del("123");
            System.out.println("删除操作:123");
        }
        
        //修改
        @GetMapping("/update")
        public Test update(){
            Test test = new Test();
            test.setUid("123");
            test.setUsername("aaaaabbbbbb");
            testService.update(test);
            System.out.println("修改操作:"+test.toString());
            return test;
        }
        
        //查询
        @GetMapping("/retrieve")
        public Test retrieve(){
            Test test = testService.retrieve("123");
            if(test != null){
                System.out.println("查询结果:" + test.toString());
            }else{
                System.out.println("查询结果:数据123不存在!");
            }   
            return test;
        }
    }
    

    最后,测试;在浏览器下输入新增、查询、修改、查询、删除、查询的地址,查看控制台运行结果;

    新增测试
    新增后查询
    修改测试
    修改后查询
    删除测试
    删除后查询
    再来看一下控制台的输出:
    新增操作:Test [uid=123, username=aa, password=null, sex=null]
    查询结果:Test [uid=123, username=aa, password=null, sex=null]
    修改操作:Test [uid=123, username=aaaaabbbbbb, password=null, sex=null]
    查询结果:Test [uid=123, username=aaaaabbbbbb, password=null, sex=null]
    删除操作:123
    查询结果:数据123不存在!
    

    相关文章

      网友评论

        本文标题:SpringBoot初次集成Redis踩坑,安装+使用

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