您现在的位置是:首页 > 缘文分享缘文分享

Redis在微服务架构中的应用

2020-11-10【缘文分享】人已围观

简介缘文分享:内心如果平静,外在就不会有风波。

Redis在微服务架构中的应用

原文链接:https://piotrminkowski.wordpress.com/2019/03/18/redis-in-microservices-architecture/

作者: PiotrMińkowski

译者:Yunooa

1.概述

Redis可以广泛用于微服务架构。它可能是您应用程序以多种不同方式利用的少数流行软件解决方案之一。根据要求,它可以充当主数据库,缓存,消息代理。虽然它也是一个键/值存储,但我们可以将它用作微服务架构中的配置服务器或发现服务器。虽然它通常被定义为内存中的数据结构,但我们也可以在持久模式下运行它。
今天,我将向您展示一些使用Redis与Spring Boot和Spring Cloud框架之上构建的微服务的示例。这些应用程序将使用Redis Pub / Sub异步通信,使用Redis作为缓存或主数据库,最后使用Redis作为配置服务器。这是说明架构的图片。

file

2.Redis作为配置服务器

如果已经使用Spring Cloud构建了微服务,您可能已经接触过Spring Cloud Config。它负责为微服务提供分布式配置模式。不幸的是,Spring Cloud Config不支持Redis作为属性源后端存储库。这就是我决定分离Spring Cloud Config项目并实现此功能的原因。我希望我的实现很快将被包含在正式的Spring Cloud版本中,但是现在你可以使用我的fork repo来运行它。它可以在我的GitHub帐户piomin / spring-cloud-config上找到。如何使用它?非常简单。让我们来看看。
目前SNAPSHOT版本的Spring Boot是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
@EnableConfigServer
public class ConfigApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ConfigApplication.class).run(args);
}
}

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

 
  1. $ 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哈希的结构。
file
该可视化相当于运行Redis CLI命令HGETALL,该命令返回散列中的所有字段和值。

 
  1. >> HGETALL driver-management
  2. {
  3. "server.port": "8100",
  4. "sample.topic.name": "trips",
  5. "spring.redis.host": "192.168.99.100"
  6. }

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

 
  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-config</artifactId>
  4. </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文件。

 
  1. spring:
  2. application:
  3. name: driver-management

3.Redis作为消息代理

现在我们可以在基于微服务的体系结构 - 消息代理中继续使用Redis的第二个用例。我们将实现一个典型的异步系统,如下图所示。微服务trip-management在创建新行程和完成当前行程后向Redis Pub / Sub发送通知。通知由两者接收,driver-management并且passenger-management订阅特定频道。
file

我们的应用非常简单。我们只需要添加以下依赖项,以便提供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>

我们应该用渠道名称和出版商注册bean。TripPublisher负责向目标主题发送消息。

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

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

 
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并设置消息监听器实现类。

 
@Configuration
public 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反序列化为对象并更改驱动程序状态。

 
@Service
public 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);
}
}
}

4.Redis作为主数据库

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

 
  1. $ 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
@EnableRedisRepositories
public class DriverConfiguration {
// logic ...
}

使用Spring Data存储库,我们没有构建任何Redis查询,只是按照Spring Data约定命名方法。有关更多详细信息,请参阅我之前的文章Spring Data Redis简介。为了我们的示例目的,我们可以使用Spring Data中实现的默认方法。这是存储库接口的声明driver-management。

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

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

 
@Configuration
@EnableRedisRepositories
public class DriverConfiguration {
...
}

Tags:Redis在微服务架构中的应用

很赞哦! ()

文章评论

    共有条评论来说两句吧...

    用户名:

    验证码:

站点信息

  • 建站时间:2019-05-15
  • 文章统计238篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 公众号:资源连接