首页 文章资讯内容详情

你知道如何在springboot中使用redis吗

2026-06-01 5 花语

本文内容纲要:

-安装redis -集成springboot -添加maven依赖 -编写springboot配置文件 -编写配置类 -使用方法 -通过注解使用 -手动控制

特别说明:本文针对的是新版springboot2.1.3,其springdata依赖为spring-boot-starter-data-redis,且其默认连接池为lettuce

  redis作为一个高性能的内存数据库,如果不会用就太落伍了,之前在node.js中用过redis,本篇记录如何将redis集成到springboot中。提供redis操作类,和注解使用redis两种方式。主要内容如下:

docker安装redis springboot集成redis 编写redis操作类 通过注解使用redis

安装redis

  通过docker安装,dockercompose编排文件如下:

#docker-compose.yml version:"2" services: redis: container_name:redis image:redis:3.2.10 ports: -"6379:6379"

  然后在docker-compose.yml所在目录使用docker-composeup-d命令,启动redis。

集成springboot

  说明:springboot版本为2.1.3

添加maven依赖

  只需添加spring-boot-starter-data-redis依赖即可,并排除lettuce依赖,然后引入jedis和jedis的依赖commons-pool2

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>

编写springboot配置文件

  配置文件如下:

server: port:8081 servlet: context-path:/sso spring: application: name:SSO cache: type:redis redis: database:0 host:192.168.226.5 port:6379 #有密码填密码,没有密码不填 password: #连接超时时间(ms) timeout:1000ms #高版本springboot中使用jedis或者lettuce jedis: pool: #连接池最大连接数(负值表示无限制) max-active:8 #连接池最大阻塞等待时间(负值无限制) max-wait:5000ms #最大空闲链接数 max-idle:8 #最小空闲链接数 min-idle:0

编写配置类

  配置类代码如下:

@EnableCaching//开启缓存 @Configuration publicclassRedisConfigextendsCachingConfigurerSupport{ /** *设置缓存管理器,这里可以配置默认过期时间等 * *@paramconnectionFactory连接池 *@return */ @Bean publicCacheManagercacheManager(RedisConnectionFactoryconnectionFactory){ RedisCacheConfigurationredisCacheConfiguration=RedisCacheConfiguration .defaultCacheConfig() .entryTtl(Duration.ofSeconds(60)); //注意:请勿使用先new配置对象,然后在调用entryTtl方法的方式来操作 //会导致配置不生效,原因是调用.entryTtl方法会返回一个新的配置对象,而不是在原来的配置对象上修改 RedisCacheWriterredisCacheWriter=RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory); RedisCacheManagermanager=newRedisCacheManager(redisCacheWriter,redisCacheConfiguration); returnmanager; } @SuppressWarnings("all") @Bean publicRedisTemplate<String,String>redisTemplate(JedisConnectionFactoryfactory){ StringRedisTemplatetemplate=newStringRedisTemplate(factory); Jackson2JsonRedisSerializerjackson2JsonRedisSerializer=newJackson2JsonRedisSerializer(Object.class); ObjectMapperom=newObjectMapper(); om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); RedisSerializerstringSerializer=newStringRedisSerializer(); template.setKeySerializer(stringSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(stringSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); returntemplate; } //使用jedis连接池建立jedis连接工厂 @Bean publicJedisConnectionFactoryjedisConnectionFactory(){ logger.info("jedisConnectionFactory:初始化了"); JedisPoolConfigconfig=newJedisPoolConfig(); config.setMaxIdle(maxIdle); config.setMinIdle(minIdle); config.setMaxWaitMillis(maxWaitMillis); config.setMaxTotal(maxActive); //链接耗尽时是否阻塞,默认true config.setBlockWhenExhausted(true); //是否启用pool的jmx管理功能,默认true config.setJmxEnabled(true); JedisConnectionFactoryfactory=newJedisConnectionFactory(); factory.setPoolConfig(config); factory.setHostName(host); factory.setPort(port); factory.setPassword(password); factory.setDatabase(database); factory.setTimeout(timeout); returnfactory; } }

使用方法

  有两种方法来进行缓存操作,一种是在方法上添加缓存注解实现各种操作,一种是手动控制。个人比较喜欢手动控制,觉得这样都在自己的掌控中。

通过注解使用

  主要有以下5个注解:

@CacheConfig:类级别缓存,设置缓存key前缀之类的 @Cacheable:触发缓存入口 @CacheEvict:触发移除缓存 @CachePut:更新缓存 @Caching:组合缓存 @CacheConfig

  该注解可以将缓存分类,它是类级别注解,主要用于给某个类的缓存全局配置,例子如下:

@CacheConfig(cacheNames="redis_test") @Service publicclassRedisService{ //.... }

上面CacheConfig会给类下通过注解生成的key加上redis_test的前缀。

@Cacheable

  方法级别注解,根据key查询缓存:

如果key不存在,将方法返回值缓存到redis中

如果key存在,直接从缓存中取值

例子如下:

/** *缓存时间,首次查询后会缓存结果,key中的值可使用表达式计算. *如不提供key,将使用默认key构造方法生成一个key *@returnlong */ @Cacheable(key="currentTime") publiclonggetTime(){ returnSystem.currentTimeMillis(); }

多次调用此段代码会发现每次返回的值都是一样的。

CachePut

  用于更新缓存,每次调用都会想db请求,缓存数据

如果key存在,更新内容 如果key不存在,插入内容

代码如下:

/** *一般用于更新查插入操作,每次都会请求db */ @CachePut(key="currentTime+#id") publiclongupdateTime(Stringid){ returnSystem.currentTimeMillis(); }

每次调用此方法都会根据key刷新redis中的缓存数据。

@CacheEvict

  根据key删除缓存中的数据。allEntries=true表示删除缓存中所有数据。

代码如下: @CacheEvict(key="currentTime+#id",allEntries=false) publicvoiddeleteTime(Stringid){ } @Caching

  本注解可将其他注解组合起来使用。比如下面的例子:

//value属性为key指定前缀 @Caching(put={@CachePut(value="user",key="name_+#user.name"), @CachePut(value="user",key="pass_+#user.password")}) publicUsertestCaching(Useruser){ returnuser; }

上面的代码执行后将在redis中插入两条记录。使用keys*将看到如下结果:

手动控制

  手动控制就相当于mybatis的手写sql语句,需要调用redisTemplate中的各种方法来进行缓存查询,缓存更新,缓存删除等操作。

  使用方法参见util/RedisUtil中的方法。redisTemplate基本可以实现所有的redis操作。

本篇原创发布于:springboot整合redis

项目源码::github

本文内容总结:安装redis,集成springboot,添加maven依赖,编写springboot配置文件,编写配置类,使用方法,通过注解使用,手动控制,

原文链接:https://www.cnblogs.com/wuyoucao/p/10941792.html