首页 > 编程 > Java > 正文

浅谈Redis在微服务架构中的几种应用场景

2019-11-26 09:02:54
字体:
来源:转载
供稿:网友

本文介绍在SpringCloud中使用Redis作为Pub/Sub异步通信、缓存或主数据库和配置服务器的三种场景应用。

Redis可以广泛用于微服务架构。它可能是您应用程序以多种不同方式利用的少数流行软件解决方案之一。根据要求,它可以充当主数据库,缓存或消息代理。虽然它也是一个键/值存储,但我们可以将它用作微服务体系结构中的配置服务器或发现服务器。虽然它通常被定义为内存中的数据结构,但我们也可以在持久模式下运行它。

这里我将向您展示一些使用Redis与Spring Boot和Spring Cloud框架之上构建的微服务的示例。这些应用程序将使用Redis Pub / Sub异步通信,使用R​​edis作为缓存或主数据库,最后使用Redis作为配置服务器。

Redis作为配置服务器

如果您已经使用Spring Cloud构建了微服务,那么您可能对Spring Cloud Config有一些经验。它负责为微服务提供分布式配置模式。

不幸的是,Spring Cloud Config不支持Redis作为属性源的后端存储库。这就是我决定分叉Spring Cloud Config项目并实现此功能的原因。

我希望我的实现很快将被包含在官方的Spring Cloud版本中,但是,现在,您可以使用我的fork repo来运行它。我们怎么用呢?非常简单。让我们来看看。

Spring Boot的当前SNAPSHOT版本2.2.0.BUILD-SNAPSHOT与我们用于Spring Cloud Config的版本相同。在构建Spring Cloud Config Server时,我们只需要包含这两个依赖项,如下所示。

<parent>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-parent</artifactId>  <version>2.2.0.BUILD-SNAPSHOT</version></parent><artifactId>config-service</artifactId><groupId>pl.piomin.services</groupId><version>1.0-SNAPSHOT</version><dependencies>  <dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-config-server</artifactId>    <version>2.2.0.BUILD-SNAPSHOT</version>  </dependency></dependencies>

默认情况下,Spring Cloud Config Server使用Git存储库后端。我们需要激活 redis配置文件以强制它使用Redis作为后端。如果您的Redis实例侦听的地址不是localhost:6379您需要使用spring.redis.*属性覆盖自动配置的连接设置 。这是我们的bootstrap.yml文件。

spring: application:  name: config-service profiles:  active: redis redis:  host: 192.168.99.100

应用程序主类应注释@EnableConfigServer:

@SpringBootApplication@EnableConfigServerpublic class ConfigApplication {  public static void main(String[] args) {    new SpringApplicationBuilder(ConfigApplication.class).run(args);  }}

在运行应用程序之前,我们需要启动Redis实例。这是将其作为Docker容器运行并在端口6379上公开的命令。

$ docker run -d --name redis -p 6379:6379 redis

每个应用程序的配置必须在密钥{spring.application.name}或{spring.application.name}-${spring.profiles.active[n]}。我们必须使用与配置属性名称对应的键创建哈希。

我们的示例应用程序driver-management使用三个配置属性:server.port用于设置HTTP侦听端口,spring.redis.host用于更改用作消息代理和数据库的默认Redis地址,以及sample.topic.name用于设置用于我们的微服务之间的异步通信的主题的名称。这是我们为driver-management使用RDBTools可视化而创建的Redis哈希的结构。

在Redis CLI 中运行HGETALL ,返回:

>> HGETALL driver-management{  "server.port": "8100",   "sample.topic.name": "trips",   "spring.redis.host": "192.168.99.100"}

在Redis中设置键值并使用redis配置文件运行Spring Cloud Config Server之后,我们需要在客户端启用分布式配置功能。要做到这一点,我们只需要包含对每个微服务的spring-cloud-starter-config依赖pom.xml。

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId></dependency>

使用最新稳定的Spring Cloud:

<dependencyManagement>  <dependencies>    <dependency>      <groupId>org.springframework.cloud</groupId>      <artifactId>spring-cloud-dependencies</artifactId>      <version>Greenwich.SR1</version>      <type>pom</type>      <scope>import</scope>    </dependency>  </dependencies></dependencyManagement>

应用程序的名称是spring.application.name在启动时从属性中获取的,因此我们需要提供以下bootstrap.yml文件。

spring: application:  name: driver-management

Redis作为消息代理

现在我们可以在基于微服务的体系结构中继续使用Redis的第二个用例 - 消息代理。我们将实现一个典型的异步系统。

微服务trip-management在创建新行程后以及完成当前行程后向Redis Pub / Sub发送通知。通知由订阅特定频道的driver-management和接收 。

我们的应用非常简单。我们只需要添加以下依赖项,以便提供REST API并与Redis Pub / Sub集成。

<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-web</artifactId></dependency><dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-data-redis</artifactId></dependency>

我们应该使用频道channel名称和发布者注册bean。TripPublisher负责向目标主题发送消息。

@Configurationpublic class TripConfiguration {  @Autowired    RedisTemplate<?, ?> redisTemplate;  @Bean    TripPublisher redisPublisher() {    return new TripPublisher(redisTemplate, topic());  }  @Bean    ChannelTopic topic() {    return new ChannelTopic("trips");  }}

TripPublisher使用RedisTemplate将消息发送到的话题。在发送之前,它会使用Jackson2JsonRedisSerializer对来自对象的每条消息转换为JSON字符串。

public class TripPublisher {  private static final Logger LOGGER = LoggerFactory.getLogger(TripPublisher.class);  RedisTemplate<?, ?> redisTemplate;  ChannelTopic topic;  public TripPublisher(RedisTemplate<?, ?> redisTemplate, ChannelTopic topic) {    this.redisTemplate = redisTemplate;    this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Trip.class));    this.topic = topic;  }  public void publish(Trip trip) throws JsonProcessingException {    LOGGER.info("Sending: {}", trip);    redisTemplate.convertAndSend(topic.getTopic(), trip);  }}

我们已经在发布者方面实现了逻辑。现在,我们可以继续在消费接受方面的代码事先。

我们有两个微服务driver-management,passenger-management,它们监听trip-management微服务发送的通知 。我们需要定义RedisMessageListenerContainerbean并设置消息监听器实现类。

@Configurationpublic class DriverConfiguration {  @Autowired    RedisConnectionFactory redisConnectionFactory;  @Bean    RedisMessageListenerContainer container() {    RedisMessageListenerContainer container = new RedisMessageListenerContainer();    container.addMessageListener(messageListener(), topic());    container.setConnectionFactory(redisConnectionFactory);    return container;  }  @Bean    MessageListenerAdapter messageListener() {    return new MessageListenerAdapter(new DriverSubscriber());  }  @Bean    ChannelTopic topic() {    return new ChannelTopic("trips");  }}

负责处理传入通知的类需要实现该 MessageListener接口。收到消息后, DriverSubscriber将其从JSON反序列化到对象并更改驱动程序的状态。

@Servicepublic class DriverSubscriber implements MessageListener {  private final Logger LOGGER = LoggerFactory.getLogger(DriverSubscriber.class);  @Autowired    DriverRepository repository;  ObjectMapper mapper = new ObjectMapper();  @Override    public void onMessage(Message message, byte[] bytes) {    try {      Trip trip = mapper.readValue(message.getBody(), Trip.class);      LOGGER.info("Message received: {}", trip.toString());      Optional<Driver> optDriver = repository.findById(trip.getDriverId());      if (optDriver.isPresent()) {        Driver driver = optDriver.get();        if (trip.getStatus() == TripStatus.DONE)                  driver.setStatus(DriverStatus.WAITING); else                  driver.setStatus(DriverStatus.BUSY);        repository.save(driver);      }    }    catch (IOException e) {      LOGGER.error("Error reading message", e);    }  }}

Redis作为主数据库

虽然使用Redis的主要目的是内存中缓存或作为键/值存储,但它也可以充当应用程序的主数据库。在这种情况下,以持久模式运行Redis是值得的。

$ docker run -d --name redis -p 6379:6379 redis redis-server --appendonly yes

实体使用哈希散列操作和mmap结构存储在Redis中。每个实体都需要一个哈希键和id。

@RedisHash("driver")public class Driver {  @Id    private long id;  private String name;  @GeoIndexed    private Point location;  private DriverStatus status;  // setters and getters ...}

幸运的是,Spring Data Redis为Redis集成提供了一个众所周知的存储库模式。要启用它,我们应该使用@EnableRedisRepositories注释配置类或主类。使用Spring存储库模式时,我们不必自己构建对Redis的任何查询。

@Configuration@EnableRedisRepositoriespublic class DriverConfiguration {  // logic ...}

使用Spring Data存储库,我们不必构建任何Redis查询,只需遵循Spring Data的约定下的名称方法。为了我们的示例目的,我们可以使用Spring Data中实现的默认方法。这是存储库接口的声明driver-management。

public interface DriverRepository extends CrudRepository<Driver, Long> {}

不要忘记通过使用@EnableRedisRepositories注释主应用程序类或配置类来启用Spring Data存储库。

@Configuration@EnableRedisRepositoriespublic class DriverConfiguration {  ...}

结论

正如我在前言中提到的,Redis在微服务架构中有各种用例。我刚刚介绍了如何与Spring Cloud和Spring Data一起使用它来提供配置服务器,消息代理和数据库。Redis通常被认为是缓存存储,但我希望在阅读本文之后,您将改变主意。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表