• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

springboot中使用redis的方法代码详解

springboot 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论

特别说明:

本文针对的是新版 spring boot 2.1.3,其 spring data 依赖为 spring-boot-starter-data-redis,且其默认连接池为 lettuce

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

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

安装 redis

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

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

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

集成 springboot

说明:springboot 版本为 2.1.3

添加 maven 依赖

只需添加spring-boot-starter-data-redis依赖即可,并排除 lettuce 依赖,然后引入 jedis 和 jedis 的依赖 commons-p本文来源gaodaima#com搞(代@码$网6ool2

<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
public class RedisConfig extends CachingConfigurerSupport {
 /**
  * 设置缓存管理器,这里可以配置默认过期时间等
  *
  * @param connectionFactory 连接池
  * @return
  */
 @Bean
 public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
  RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
    .defaultCacheConfig()
    .entryTtl(Duration.ofSeconds(60));
  //注意:请勿使用先new 配置对象,然后在调用entryTtl方法的方式来操作
  //会导致配置不生效,原因是调用.entryTtl方法会返回一个新的配置对象,而不是在原来的配置对象上修改

  RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
  RedisCacheManager manager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
  return manager;
 }
 @SuppressWarnings("all")
 @Bean
 public RedisTemplate<String, String> redisTemplate(JedisConnectionFactory factory) {
  StringRedisTemplate template = new StringRedisTemplate(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);
  RedisSerializer stringSerializer = new StringRedisSerializer();
  template.setKeySerializer(stringSerializer);
  template.setValueSerializer(jackson2JsonRedisSerializer);
  template.setHashKeySerializer(stringSerializer);
  template.setHashValueSerializer(jackson2JsonRedisSerializer);
  template.afterPropertiesSet();
  return template;
 }

 //使用jedis连接池建立jedis连接工厂
 @Bean
 public JedisConnectionFactory jedisConnectionFactory() {
  logger.info("jedisConnectionFactory:初始化了");
  JedisPoolConfig config = new JedisPoolConfig();
  config.setMaxIdle(maxIdle);
  config.setMinIdle(minIdle);
  config.setMaxWaitMillis(maxWaitMillis);
  config.setMaxTotal(maxActive);
  //链接耗尽时是否阻塞,默认true
  config.setBlockWhenExhausted(true);
  //是否启用pool的jmx管理功能,默认true
  config.setJmxEnabled(true);
  JedisConnectionFactory factory = new JedisConnectionFactory();
  factory.setPoolConfig(config);
  factory.setHostName(host);
  factory.setPort(port);
  factory.setPassword(password);
  factory.setDatabase(database);
  factory.setTimeout(timeout);
  return factory;
 }
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:springboot中使用redis的方法代码详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址