首页 > 编程知识 正文

springboot redis配置文件,application.yml配置redis

时间:2023-05-03 13:56:33 阅读:158954 作者:95

前言最近,我用redis在springboot上做项目。 第一次使用yml格式作为配置文件。 在这里记录我的使用过程和错误情况。 希望你能节约时间,不要踩漏洞。

本文的第一步是maven引入依赖。

作为ependencygroupidredis.clients/groupidartifactidjedis/artifact id/dependency的第二步骤,配置application.yml文件的redis配置

spring : # redis redis 3360 host :127.0.0.1 port :6379 time out :3 # password : pool : min idle 33601 maxidle 33601 max 不这样做的话,形式会错的。 另外,请特别注意缩进。 yml的所有级别关系都是缩进进行的。 这是与xml的区别。 例如,此处redis是属于spring下的子集,host、port、timeout、pool是redis的子集,当用. properties文件写入时,此处的host是spring.redis

在步骤3中,将读取redis设置类添加到springboot中。

springboot本身有一个强有力的注释@ConfigurationProperties来读取设置。 只需在相应的类中添加注释并指定前缀,就可以自动读取yml文件中此前缀的属性。

以下是读取配置的类。 Getter、Setter、NoArgsConstructor注释都是采用lombok简化码的结果,省略了手动生成Getter、Setter、构建方法的步骤。 关于lombok,可以看到我的另一个博客“lombok插件”。

/* * * createdbymakersyon 2019 */@ component @ component @ configuration properties (prefix=' spring.redis ' ) getter @ settter @ ner @ nener @ nent 私有时间输出; //秒私有字符串密码; private HashMapString,String pool=new HashMap (; 需要注意的是,pool下有子集。 但是,我们的前缀被设置为spring.redis。 写下pool下的属性名称,一定无法读取。 (我从一开始就这么做了…… 在此,通过一个HashMap存储pool属性的集合,为了取得对应的值,使用HashMap的get (属性名)方法即可。

在第四步中,封装并获取连接池类。 此类读取yml文件的redis配置,并生成具有这些属性的JedisPool。 您可以将获取相应属性的代码与上面yml的属性设置结合起来查看。

/* * * createdbymakersyon 2019 */@ servicepublicclassredispoolfactory { @ autowiredredisconfigredisconfig; @ beanpublicjedispooljedisfactory () jedispoolconfigpoolconfig=newjedispoolconfig ); poolconfig.setmaxtotal (integer.value of ) redisconfig.getpool ).get ) ' maxactive ' ); poolconfig.set maxidle (integer.value of (redis config.get pool ).get ) ' maxidle ); poolconfig.setmaxwaitmillis (integer.value of (redis config.get pool ).get ) ' maxwait ' ) * 1000 ); //注意单位为ms,用于转换单位poolconfig.setminidle (integer.value of ) redisconfig.getpool ).get ) ' minidle ' ) redisConfig.getPort )、redisConfig.getTimeout ) *1000 }结语到此为止,springboot与redis的集成已完成。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。