当前位置:   article > 正文

Spring Boot 整合 Redis 超详细教程_spring boot redis

spring boot redis


前言

Redis 是一种高性能的键值存储数据库,而 Spring Boot 是一个简化了开发过程的 Java 框架。将两者结合,可以轻松地在 Spring Boot 项目中使用 Redis 来实现数据缓存、会话管理和分布式锁等功能。

话不多说直接干货!!!


一、pom.xml 中添加 Redis 依赖

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>
  • 1
  • 2
  • 3
  • 4

二、配置 Redis 连接信息

application.yml 配置文件中添加 Redis 连接信息,根据自己 Redis 服务器配置,修改主机和端口信息

spring:
    redis:
       # 地址
       host: localhost
       # 端口,默认为6379
       port: 6379
       # 数据库索引
       database: 0
       # 密码
       password: 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

三.使用 RedisTemplate 进行操作

1、RedisTemplate Bean配置类

@Configuration
public class RedisConfiguration {
	
	/**
	 JSON 序列化器来对值进行序列化和反序列化
	*/
	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory cf) {
	  RedisTemplate<String, Object> rt= new RedisTemplate<>();
	  rt.setConnectionFactory(cf);
	  rt.setKeySerializer(new StringRedisSerializer());
	  rt.setValueSerializer(new GenericJackson2JsonRedisSerializer());
	  return rt;
	}
	}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

2、注入 RedisTemplate

	/**
	在服务类或控制器中注入 RedisTemplate
	*/
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
  • 1
  • 2
  • 3
  • 4
  • 5

3、 Redis 操作

//使用注入的 RedisTemplate 来进行 Redis 操作,设置键值对、获取值

	/** 
	设置键值对
	*/
	redisTemplate.opsForValue().set("key", "value");
	
	/**  
	获取值
	*/
	String value = (String) redisTemplate.opsForValue().get("key");

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

四. Spring Cache 简化缓存操作

1、pom.xml中添加 Spring Cache 依赖

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>
  • 1
  • 2
  • 3
  • 4

2、启用类添加缓存支持注解

	//开启spring cache
	@EnableCaching
	@SpringBootApplication
	public class Application {
	  // ...
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3、使用缓存注解

@Service
public class redisService {

  @Cacheable(value = "cacheName", key = "#code")
  public Object getData(String id) {
    // 从数据库或其他数据源获取数据
    return data;
  }

  @CachePut(value = "cacheName", key = "#code")
  public Object updateData(String id, Object newData) {
    // 更新数据库或其他数据源的数据
    return newData;
  }

  @CacheEvict(value = "cacheName", key = "#code")
  public void deleteData(String id) {
    // 删除数据库或其他数据源的数据
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

五. 实现分布式锁 Redisson

1、pom.xml中添加 Redisson 依赖

  <dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.16.3</version>
  </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2、yml中进行Redisson配置

spring:
    redis:
       # 地址
       redisson: 
       	config: classpath:redisson-single.yml #在 redisson-single.yml 配置文件中配置 Redisson 的连接信息
  • 1
  • 2
  • 3
  • 4
  • 5

3、Redisson 获取锁

	@Autowired
	private RedissonClient redissonClient;
	
	public void doSomething() {
	  RLock lock = redissonClient.getLock("lockName");
	  try {
	    lock.lock();
	    // 执行需要加锁的操作
	  } finally {
	    lock.unlock();
	  }
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

六. Redis相关配置

1、redis.conf连接池配置

打开 Redis 配置文件 redis.conf

# 最大连接数
maxclients 10000
# TCP 连接的队列长度
tcp-backlog 500
# 连接池中的最大空闲连接数
maxidle 100
# 连接池中的最小空闲连接数
minidle 10
# 连接超时时间(毫秒)
timeout 3000
# 是否开启 TCP 连接的保活机制
tcp-keepalive 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2、客户端Jedis连接池配置对象JedisPoolConfig配置

@Configuration
public class JedisConfig {
	
	 @Bean
	 public JedisPoolConfig jedisPoolConfig() {
	   JedisPoolConfig poolConfig = new JedisPoolConfig();
	   poolConfig.setMaxTotal(10000);
	   poolConfig.setMaxIdle(100);
	   poolConfig.setMinIdle(10);
	   poolConfig.setMaxWaitMillis(3000);
	   // 其他配置项设置
	   return poolConfig;
	 }
	
	 @Bean
	 public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig poolConfig) {
	   RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
	   config.setHostName("127.0.0.1");
	   config.setPort(6379);
	   // 其他 Redis 配置项设置
	   JedisClientConfiguration clientConfig = JedisClientConfiguration.builder()
	       .usePooling().poolConfig(poolConfig)
	       .build();
	   return new JedisConnectionFactory(config, clientConfig);
	 }
	
	 @Bean
	 public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory connectionFactory) {
	   RedisTemplate<String, Object> template = new RedisTemplate<>();
	   template.setConnectionFactory(connectionFactory);
	   template.setKeySerializer(new StringRedisSerializer());
	   template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
	   return template;
	 }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

3、超时时间设置

1、在 Redis 配置文件中设置 timeout 参数,用于控制 Redis 操作的超时时间,以防止长时间的阻塞或无响应操作

timeout 5000 //单位为毫秒
  • 1

2、通过 JedisClientConfiguration 进行配置,将读取操作的超时时间设置为 5秒

	@Bean
	public JedisClientConfiguration jedisClientConfiguration() {
	  Duration timeout = Duration.ofSeconds(5);
	  return JedisClientConfiguration.builder()
	      .readTimeout(timeout)
	      .build();
	}
	
	@Bean
	public JedisConnectionFactory jedisConnectionFactory(JedisClientConfiguration clientConfig) {
	  // 其他配置项设置
	  return new JedisConnectionFactory(config, clientConfig);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/799482
推荐阅读
相关标签
  

闽ICP备14008679号