Spring整合Redis(二)----关于连接工厂

【Spring连载】使用Spring Data访问Redis(二)----关于连接工厂

一、概述

使用Redis和Spring的首要任务之一是通过IoC容器连接到存储。为此,需要一个Java连接器(或绑定)。无论你选择哪个库,你只需要使用一组Spring Data Redis api(它在所有连接器上的行为一致)。org.springframework.data.redis.connection包及其RedisConnection和RedisConnectionFactory接口,用于与Redis一同工作,并检索Redis的active连接。

二、RedisConnection和RedisConnectionFactory

RedisConnection为Redis通信提供了核心模块。它还自动将底层连接库异常转换为与Spring一致的DAO异常层次结构,这样你就可以在不更改任何代码的情况下切换连接器,因为操作语义保持不变。
对于需要native library API的情况,RedisConnection提供了一个专用方法(getNativeConnection),该方法返回用于通信的原始底层对象。
Active RedisConnection对象是通过RedisConnectionFactory创建的。此外,工厂充当PersistenceExceptionTranslator对象,这意味着一旦声明,它们就可以进行透明的异常转换。例如,您可以通过使用@Repository注解和AOP来进行异常转换。有关更多信息,请参阅Spring Framework文档中的专门描述
RedisConnection类不是线程安全的。虽然底层的本机连接,如Lettuce的StatefulRedisConnection,可能是线程安全的,但Spring Data Redis的LettuceConnection类本身不是。因此,不应在多个线程之间共享RedisConnection的实例。对于事务性或阻塞Redis操作和命令(如BLPOP)尤其如此。例如,在事务和pipelining操作中,RedisConnection保持不受保护的可变状态以正确完成操作,从而使它在多线程环境使用变得不安全。这是经过设计的。
如果出于性能或其他原因,需要在多个线程之间共享(有状态)Redis资源,如连接,则应获取native连接并直接使用Redis客户端库(驱动程序)API。或者,你可以使用RedisTemplate,它以线程安全的方式获取和管理operations (和Redis命令)的连接。有关更多详细信息,请参阅RedisTemplate文档
根据底层配置,工厂可以返回新连接或现有连接(当使用池或共享native连接时)。
使用RedisConnectionFactory最简单的方法是通过IoC容器配置适当的连接器,并将其注入调用类。
但是,目前并不是所有的连接器都支持Redis的所有功能。在基础库不支持的Connection API上调用方法时,将引发UnsupportedOperationException。以下概述解释了各个Redis连接器支持的功能:
表1: 各Redis连接器的功能可用性

支持特性LettuceJedis
Standalone 连接
Master/Replica 连接
Redis SentinelMaster Lookup, Sentinel Authentication, Replica ReadsMaster Lookup
Redis ClusterCluster Connections, Cluster Node Connections, Replica ReadsCluster Connections, Cluster Node Connections
传输通道TCP, OS-native TCP (epoll, kqueue), Unix Domain SocketsTCP
连接池✓(使用commons-pool2)✓(使用commons-pool2)
其他连接特性Singleton-connection sharing for non-blocking commandsPipelining 和Transactions 互斥。不能在pipeline/transactions使用 server/connection 命令 .
SSL 支持
Pub/Sub
Pipelining✓(Pipelining 和 Transactions互斥)
事务✓(Pipelining 和 Transactions互斥)
Datatype 支持Key, String, List, Set, Sorted Set, Hash, Server, Stream, Scripting, Geo, HyperLogLogKey, String, List, Set, Sorted Set, Hash, Server, Stream, Scripting, Geo, HyperLogLog
Reactive (non-blocking) API

三、配置 Lettuce 连接器

Lettuce是一个基于Netty的开源连接器,由Spring Data Redis通过org.springframework.data.redis.connection.lettuce包支持。将以下依赖内容添加到pom.xml文件中:

<dependencies>

  <!-- other dependency elements omitted -->

  <dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>6.3.1.RELEASE</version>
  </dependency>

</dependencies>

下面的例子展示了如何创建一个新的Lettuce连接工厂:

@Configuration
class AppConfig {

  @Bean
  public LettuceConnectionFactory redisConnectionFactory() {

    return new LettuceConnectionFactory(new RedisStandaloneConfiguration("server", 6379));
  }
}

还有一些Lettuce特定的连接参数可以调整。默认情况下,由LettuceConnectionFactory创建的所有LettuceConnection实例共享相同的线程安全native连接,用于所有非阻塞和非事务操作。若要每次使用专用连接,请将shareNativeConnection设置为false。如果shareNativeConnection设置为false,则还可以将LettuceConnectionFactory配置为使用LettucePool来池化阻塞和事务连接或所有连接。
以下示例展示了使用LettuceClientConfigurationBuilder的更复杂的配置,包括SSL和超时:

@Bean
public LettuceConnectionFactory lettuceConnectionFactory() {

  LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
    .useSsl().and()
    .commandTimeout(Duration.ofSeconds(2))
    .shutdownTimeout(Duration.ZERO)
    .build();

  return new LettuceConnectionFactory(new RedisStandaloneConfiguration("localhost", 6379), clientConfig);
}

有关更详细的客户端配置调整,请参阅LettuceClientConfiguration
Lettuce集成了Netty的native transports,允许您使用Unix domain sockets与Redis通信。确保包含与运行时环境匹配的适当native传输依赖项。下面的例子展示了如何在/var/run/redis.sock为Unix domain socket创建一个Lettuce Connection工厂:

@Configuration
class AppConfig {

  @Bean
  public LettuceConnectionFactory redisConnectionFactory() {

    return new LettuceConnectionFactory(new RedisSocketConfiguration("/var/run/redis.sock"));
  }
}

Netty目前支持用于OS-native传输的epoll (Linux)和kqueue (BSD/macOS)接口。

四、配置 Jedis 连接器

Jedis是一个community-driven的连接器,由Spring Data Redis模块通过org.springframework.data.redis.connection.jedis包支持。
将以下依赖内容添加到pom.xml文件中:

<dependencies>

  <!-- other dependency elements omitted -->

  <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>5.0.2</version>
  </dependency>

</dependencies>

以最简单的形式展现,Jedis 的配置如下:

@Configuration
class AppConfig {

  @Bean
  public JedisConnectionFactory redisConnectionFactory() {
    return new JedisConnectionFactory();
  }
}

但是,对于生产使用,你可能需要调整主机或密码等设置,如下面的示例所示:

@Configuration
class RedisConfiguration {

  @Bean
  public JedisConnectionFactory redisConnectionFactory() {

    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("server", 6379);
    return new JedisConnectionFactory(config);
  }
}
  • 24
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,关于springboot整合redis的问题,我可以回答。SpringBoot是一种基于Spring框架的快速开发框架,可以快速集成各种组件,其中包括Redis。要整合Redis,需要在SpringBoot项目的pom.xml文件中添加Redis的依赖,同时在配置文件中添加Redis的配置信息。具体的步骤可以参考SpringBoot官方文档或者一些在线教程。 ### 回答2: Spring Boot整合Redis可以通过以下步骤实现: 1. 首先,在pom.xml文件中添加Redis相关的依赖项。可以使用Spring Data Redis依赖(spring-boot-starter-data-redis)和Jedis依赖(jedis)。 2. 创建Redis的配置文件,可以在application.properties或application.yml中配置Redis的主机名、端口号、密码等信息。 3. 创建一个配置类,用于配置Redis连接工厂Redis模板。可以通过使用`@Configuration`注解和`redisConnectionFactory()`方法来配置Redis连接工厂,通过使用`@Bean`注解和`redisTemplate()`方法来配置Redis模板。 4. 创建一个服务类,用于实现对Redis的操作。可以使用Spring Data Redis提供的RedisTemplate类来实现常见的操作,如存储数据、获取数据、删除数据等。 5. 在需要使用Redis的地方,可以通过依赖注入的方式来使用Redis服务。 以下是一个简单的示例代码: 1. pom.xml文件中添加依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> ``` 2. application.properties中配置Redis信息: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 3. 创建Redis的配置类: ```java @Configuration public class RedisConfig { @Bean JedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName("127.0.0.1"); redisStandaloneConfiguration.setPort(6379); return new JedisConnectionFactory(redisStandaloneConfiguration); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory()); return template; } } ``` 4. 创建Redis的服务类: ```java @Service public class RedisService { @Autowired private RedisTemplate<String, Object> redisTemplate; public void setValue(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object getValue(String key) { return redisTemplate.opsForValue().get(key); } public void deleteValue(String key) { redisTemplate.delete(key); } } ``` 5. 在需要使用Redis的地方,可以通过依赖注入RedisService来使用Redis服务: ```java @RestController public class ExampleController { @Autowired private RedisService redisService; @GetMapping("/example") public String example() { redisService.setValue("name", "John"); String name = (String) redisService.getValue("name"); redisService.deleteValue("name"); return name; } } ``` 通过以上步骤,就可以在Spring Boot应用中使用Redis进行数据存储、获取和删除等操作了。 ### 回答3: Spring Boot是一个用于创建和构建Spring应用程序的开源框架。它简化了Spring应用程序的开发过程,并提供了各种开箱即用的功能和集成。Redis是一个流行的用于缓存和存储数据的内存数据库。下面是如何在Spring Boot应用程序中整合Redis的步骤: 1. 添加依赖:在项目的pom.xml文件中添加Redis的依赖项。可以使用Spring Boot提供的spring-boot-starter-data-redis依赖项。在构建工具Maven中,可以通过以下方式添加依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接:在Spring Boot的配置文件中,配置Redis连接信息,包括主机名、端口号、密码等。可以使用如下配置示例: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 3. 创建RedisTemplate bean:在Spring Boot的配置类中,创建RedisTemplate的bean。RedisTemplate是Spring提供的用于与Redis进行交互的工具类。可以使用如下方式创建bean: ```java @Configuration public class RedisConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.password}") private String password; @Bean public RedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port); config.setPassword(RedisPassword.of(password)); return new LettuceConnectionFactory(config); } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; } } ``` 4. 使用RedisTemplate:在需要使用Redis的地方,注入RedisTemplate并使用其提供的方法来操作Redis。例如,可以在服务类中使用RedisTemplate进行数据的读取和写入操作: ```java @Service public class UserService { @Autowired private RedisTemplate<String, Object> redisTemplate; public User getUserById(String userId) { String key = "user:" + userId; return (User) redisTemplate.opsForValue().get(key); } public void saveUser(User user) { String key = "user:" + user.getId(); redisTemplate.opsForValue().set(key, user); } } ``` 通过以上步骤,就可以在Spring Boot应用程序中成功地整合Redis,并通过RedisTemplate进行数据的读写操作。这样可以更加方便地利用Redis的优势来提升应用程序的性能和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值