Redis 重要吗?重要!

阅读文本大概需要3分钟。

作者:PiotrMińkowski
译者:Yunooa

原文链接:http://www.spring4all.com/article/6843

1.概述

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

2.Redis作为配置服务器

如果已经使用Spring Cloud构建了微服务,您可能已经接触过Spring Cloud Config。它负责为微服务提供分布式配置模式。不幸的是,Spring Cloud Config不支持Redis作为属性源后端存储库。这就是我决定fork Spring Cloud Config项目并实现此功能的原因。我希望我的实现很快将被包含在正式的Spring Cloud版本中,但是现在你可以使用我的分支的仓库来运行它。它可以在我的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上公开的命令。

$ 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

3.Redis作为消息代理

现在我们可以在基于微服务的体系结构 - 消息代理中继续使用Redis的第二个用例。我们将实现一个典型的异步系统,如下图所示。微服务trip-management在创建新行程和完成当前行程后向Redis Pub / Sub发送通知。该通知由订阅特定渠道的driver-management和passenger-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 name)和发布者(publisher)注册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将消息发送到的Topic。在发送前,它会使用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);
    }
}

我们已经实现了发布者(publisher)端的逻辑。现在,我们继续实现订阅者(subscriber)的逻辑。我们有两个微服务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。

$ 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中声明的存储库接口 (repository interface)。

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

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

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

5.结论

正如我在前言中提到的,Redis在微服务架构中有各种用例。我刚刚介绍了如何与Spring Cloud和Spring Data一起使用它来提供配置服务器,消息代理和数据库。Redis通常被认为是一个缓存,但我希望在阅读完这篇文章后你会改变主意。示例应用程序源代码在GitHub上通常可用:https://github.com/piomin/sample-redis-microservices.git。

由于能力有限,若有错误或者不当之处,还请大家批评指正,一起学习交流!

-The End-

往期精彩

01 漫谈发版哪些事,好课程推荐

02 Linux的常用最危险的命令

03 精讲Spring&nbsp;Boot—入门+进阶+实例

04 优秀的Java程序员必须了解的GC哪些

05 互联网支付系统整体架构详解

关注我

每天进步一点点

很干!在看吗?☟

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值