Micro Services Architecture - decoupling for business use Redis properties

background:

    Next to the article, the article is talking about how to use the event mechanism ApplicationContext to achieve business decoupling, and this can only act in monomer applications. In the moment so prevalent in micro-service architecture, we want to re-use this program to do business decoupling is not possible, we also mentioned, is now more popular solution is to use a message queue to complete, such as the now popular RabbitMQ, RocketMQ, ActiveMQ, Kafka.
    Of course, we can also use Redis queue to complete, it is not in question. Just my own Ali cloud, ready for a redis, we just use Redis to solve it. Redis provides a production / consumption patterns and publish / subscribe model. Mention here, one for those patterns of production and consumption, as only a consumer to consumer: for example, a user registered only send SMS tips. And our previous example is one to many, that is, registered users need to send text messages and send e-mail, so we will use publish-subscribe mode, just subscribe to a channel, all subscribers receive the message of this channel, then this consume. Then start it -
    when it comes to micro-services we think Spring Cloud, but we are now decoupled direct calls between business, no service, so we only use Spring Boot directly micro-service architecture can do. Simply divided into four modules, the user module (hyf-user), SMS module (hyf-message), the message module (hyf-mail), public class module (hyf-encapsulation).

Start:

1, project structure shown below:

2, because of the use Redis, we first have to introduce Redis its dependencies:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
3, and write the configuration in application.properties:
# redis服务端口
spring.redis.port=6379
# redis的服务地址
spring.redis.host=127.0.0.1
# 如果redis设置了密码这里也要配上
spring.redis.password=xxx
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0
4. Release information:

Service users to directly call the default StringRedisTemplate can post messages to the designated channel

/**
 * @author Howinfun
 * @desc 用户Service
 * @date 2019/5/13
 */
@Service
@Slf4j
@AllArgsConstructor
public class UserService {
 
    private StringRedisTemplate stringRedisTemplate;
 
    /**
     * 用户注册
     * @param user
     */
    public void registerUser(User user){
        log.info("用户:"+user.getName()+"注册成功");
        // 给redis的channel中发布消息
        String userInfo = JSON.toJSONString(user);
        stringRedisTemplate.convertAndSend(UserConstants.USER_REGISTER,userInfo);
    }
}
5, subscribe to channels:

    1, subscribe to a little trouble, first of all abstract interface information a consumer:

public interface AbstractReceiver {
    // 消费消息的方法
    void receiveMessage(Object message);
}

   2, then send text messages need to create a class to implement this interface, and then implement your own business logic (send mail empathy) inside the overridden method:

/**
 * @author Howinfun
 * @desc
 * @date 2019/5/14
 */
@Component
public class MessageReceiver implements AbstractReceiver {
    @Autowired
    private MessageService messageService;
    @Override
    public void receiveMessage(Object message) {
        User user = JSON.parseObject((String) message, User.class);
        // 发送短信的业务逻辑
        messageService.sendMessage(user);
    }
}

   3, and then need to get a subscription to SMS configuration class (Similarly send mail):

/**
 * @author Howinfun
 * @desc
 * @date 2019/5/14
 */
@Configuration
public class RedisConfig {
 
    /**
     * redis消息监听器容器
     * 可以添加多个监听不同话题的redis监听器,只需要把消息监听器和相应的消息订阅处理器绑定,该消息监听器
     * 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
     * @param messageListener
     * @return
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter messageListener) {
 
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //mailListener订阅了一个叫user:register 的通道
        container.addMessageListener(messageListener, new PatternTopic(UserConstants.USER_REGISTER));
        return container;
    }
 
    /**
     * 消息监听器适配器,绑定消息处理器,利用反射技术调用消息处理器的业务方法
     * @param receiver
     * @return
     */
    @Bean
    MessageListenerAdapter messageListener(MessageReceiver receiver) {
        //这个地方 是给messageListenerAdapter 传入一个消息接受的处理器,利用反射的方法调用“receiveMessage”
        //MessageListenerAdapter提供的默认调用处理器的方法是handleMessage 可以自己到源码里面看
        // 所以如果我们定义的方法不是这个,需要在构造函数这添加上
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
}
6, finally we can start the project to test it, we can see already a success:

hyf-user console:

2019-05-15 09:55:16.493  INFO 13672 --- [nio-8080-exec-2] com.hyf.user.service.UserService         : 用户:howinfun注册成功
2019-05-15 09:55:16.626  INFO 13672 --- [nio-8080-exec-2] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2019-05-15 09:55:16.627  INFO 13672 --- [nio-8080-exec-2] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library

hyf-message console:

2019-05-15 09:55:17.422  INFO 8088 --- [    container-2] com.hyf.message.service.MessageService   : 给用户howinfun发送短信,手机号码为:12345678900

hyf-mail Console:

2019-05-15 09:55:17.422  INFO 15352 --- [    container-2] com.hyf.mail.service.MailService         : 给用户howinfun发送邮件,EMail为:[email protected]

At last

Because do not want too voluminous, so just put the core code, requires detailed knowledge of the code can cloud point of view: Redis solve business decoupling source
may be asked some students, if redis hang of it, it would mean that no We have launched SMS and launch mail? The answer is right ~ ha ha ha, of course no hanging was sent. But for this correlation is not strong so-called nothing, not registering your SMS is not particularly a big thing, but then, if the project is electricity supplier, orders and reduce inventory but stronger consistency, then what's the plan , reference https://mp.weixin.qq.com/s/FAlv-qE1jjiiF0JPoMVcWA?

Guess you like

Origin www.cnblogs.com/Howinfun/p/11612770.html