Micro Services Architecture Case (04): middleware integration, public service package

This article Source: GitHub · Click here || GitEE · Click here

更新进度(共6节):

01: Introduction to Project technology selection, architecture illustration

02: business architecture design, hierarchical management system

03: Database selection, design and planning business data

04: middleware integration, public service management

I. Introduction Middleware

Middleware is a kind of basic software, which belongs to a very high software reusability. In between the operating system and software applications. Is an independent software system, can also be a public service program, distributed architecture of the system by means of middleware can share resources between different technologies or different services directly transmit information. Middleware-bit operating systems, management of computer resources and network communications. It is connected to two separate independent systems or application software, for example:

  1. Middleware message queue, the message is asynchronously transferred between the two services;
  2. Hot intermediate data cache, cache integrated systems, improve the response speed of the program;
  3. Nginx middleware to provide load balancing, proxy services, and other functions;

Second, the introduction of public services

Public service, by definition is common within the system services, such as user authentication, messaging, monitoring and early warning, gateway services.

Micro Services Architecture Case (04): middleware integration, public service package

The case of middleware and public services are based on Feignproviding service interface in a uniform manner.

Third, the middleware integration

1, messaging middleware

  • RocketMqBrief introduction

RocketMqIs a distributed messaging middleware queue model, there are two core roles: news producers and news consumers. As one of the core components of highly concurrent systems, business systems can help deconstruct improve system stability.

  • Application Process

1, news producers

@Component
public class MsgSendService {
    @Resource
    private ProducerConfig producerConfig ;
    public void sendMsg (MsgWrap msgWrap) {
        producerConfig.sendMsg(msgWrap.getGroup(),msgWrap.getTopic(),
                               msgWrap.getTag(),msgWrap.getContent());
    }
}

2, message consumer

@Component
@Consumer(group = MsgRoute.husky_group_1,
          topic = MsgRoute.husky_topic_1 ,
          tag = MsgRoute.husky_tag_1)
public class UserSearchListener implements MsgReadService {
    @Resource
    private BookEsAnalyFeign bookEsAnalyFeign ;
    @Override
    public void readMsg(String msg) throws Exception {
        LOGGER.info("【用户搜索消息监听 Msg】:{}",msg) ;
        // 转发请求数据分析服务
        bookEsAnalyFeign.sendBookEsMsg(msg);
    }
}

3, to provide Feignan interface

@RestController
public class UserSearchController implements UserSearchFeign {
    @Resource
    private SendMsgService sendMsgService ;
    @Override
    public void sendBookSearch(String msgContent) {
        MsgWrap msgWrap = new MsgWrap() ;
        msgWrap.setContent(msgContent);
        msgWrap.setGroup(MsgRoute.husky_group_1);
        msgWrap.setTopic(MsgRoute.husky_topic_1);
        msgWrap.setTag(MsgRoute.husky_tag_1);
        sendMsgService.sendMsg(msgWrap);
    }
}

2, the cache middleware

  • RedisBrief introduction

RedisIt is a high-performance memory-based key-valuedatabase. Provide various scenarios for high concurrency support system: data cache hot, counter flow and the like clipping.

  • Application Process

1, the package operation method

@Service
public class RedisServiceImpl implements RedisService {
    @Resource
    private RedisTemplate<Object,Object> redisTemplate ;
    @Override
    public boolean set(Object key, Object value) {
        boolean redisFlag = true ;
        try {
            redisTemplate.opsForValue().set(key,value);
        } catch (Exception e){
            redisFlag = false ;
            e.printStackTrace();
        }
        return redisFlag ;
    }
    @Override
    public boolean set(Object key,Object value, long expire) {
        boolean redisFlag = true ;
        try {
            redisTemplate.opsForValue().set(key,value,expire,TimeUnit.SECONDS);
        } catch (Exception e){
            redisFlag = false ;
            e.printStackTrace();
        }
        return redisFlag ;
    }
    @Override
    public String get(Object key) {
        String value = null ;
        try {
            value = String.valueOf(redisTemplate.opsForValue().get(key)) ;
        } catch (Exception e){
            e.printStackTrace();
        }
        return value ;
    }
}

2, to provide Feignservices

@RestController
public class RedisController implements RedisFeign {
    @Resource
    private RedisService redisService ;
    @Override
    public boolean set (String key, String value) {
        return redisService.set(key,value) ;
    }
    @Override
    public boolean setTimeOut (String key, String value,long expire){
        return redisService.set(key,value,expire) ;
    }
    @Override
    public String get (String key) {
        return redisService.get(key) ;
    }
}

3, search elements middleware

  • ESSearch description

ElasticSearchIt is a search server based on Lucene. It provides a distributed multi-user capabilities of full-text search engine, based on RESTfulthe web interface. It is a popular enterprise search engine.

  • Application Process

1, the package operation method

@Service
public class BookInfoEsServiceImpl implements BookInfoEsService {
    @Resource
    private BookInfoRepository bookInfoRepository ;
    @Override
    public void batchSave(List<EsBookInfo> bookInfoList) {
        bookInfoRepository.saveAll(bookInfoList) ;
    }
    @Override
    public List<EsBookInfo> queryList() {
        Iterable<EsBookInfo> bookInfoIterable = bookInfoRepository.findAll() ;
        List<EsBookInfo> esBookInfoList = Lists.newArrayList(bookInfoIterable) ;
        if (esBookInfoList == null){
            esBookInfoList = new ArrayList<>() ;
        }
        return esBookInfoList;
    }
    @Override
    public List<EsBookInfo> getByKeyWord(String keyWord) {
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(keyWord);
        Iterable<EsBookInfo> bookInfoIterable = bookInfoRepository.search(builder) ;
        List<EsBookInfo> esBookInfoList = Lists.newArrayList(bookInfoIterable) ;
        if (esBookInfoList == null){
            esBookInfoList = new ArrayList<>() ;
        }
        return esBookInfoList ;
    }
}

2, to provide Feignservices

@RestController
public class BookInfoEsController implements BookInfoEsFeign {
    @Resource
    private BookInfoEsService bookInfoEsService ;
    @Override
    public void batchSave(List<EsBookInfo> bookInfoList) {
        bookInfoEsService.batchSave(bookInfoList);
    }
    @Override
    public List<EsBookInfo> queryList() {
        return bookInfoEsService.queryList();
    }
    @Override
    public List<EsBookInfo> getByKeyWord(String keyWord) {
        return bookInfoEsService.getByKeyWord(keyWord);
    }
}

4, timer middleware

  • Quartz Brief introduction

QuartzIt is a Javaframe open task scheduling prepared, by setting the trigger timing of a job run rules, control execution time of the task. Wherein quartzthe cluster through failover and load balancing function, the scheduler can give bring high availability and scalability.

  • Application Process
@Component("SendMsgJob")
public class SendMsgJob implements TaskJobService {
    @Resource
    private SendEmailFeign sendEmailFeign ;
    @Override
    public void run(String param) {
        String nowDate = TimeUtil.formatDate(new Date(),TimeUtil.FORMAT_01) ;
        LOGGER.info("SendMsgJob Execute Time:{}",nowDate);
        sendEmailFeign.sendEmail("","定时邮件通知",""+nowDate);
    }
}

Fourth, the Public Service Management

1, Token Service

  • TokenIntro

Through a common Tokenmanagement service, make the management of user identities to access the system: the identity token creation, validation, and refreshing.

  • Application Process

1, the package operation method

@Service
public class UserTokenServiceImpl implements UserTokenService {
    @Resource
    private UserBaseMapper userBaseMapper ;
    @Resource
    private RedisFeign redisFeign ;
    @Override
    public String getToken(String userName, String passWord) throws Exception {
        UserBaseExample example = new UserBaseExample() ;
        example.createCriteria().andUserNameEqualTo(userName) ;
        UserBase userBase = selectByExample(example) ;
        if (userBase != null){
            String secrete = userBase.getPassWord() ;
            if (secrete.equals(passWord)) {
                // 返回 Token
                String value = userBase.getId().toString() ;
                String publicKeyStr = RsaCryptUtil.getKey(RsaCryptUtil.PUB_KEY) ;
                String token = RsaCryptUtil.encrypt(RsaCryptUtil.createPublicKey(publicKeyStr),value.getBytes()) ;
                String key = RedisUtil.formatUserTokenKey(userBase.getId()) ;
                redisFeign.setTimeOut(key,token, Constant.USER_TOKEN_EXPIRE) ;
                return token ;
            }
        }
        return null;
    }
    @Override
    public Integer verifyToken(String token) throws Exception {
        String privateKeyStr = RsaCryptUtil.getKey(RsaCryptUtil.PRI_KEY) ;
        String userId = RsaCryptUtil.decrypt(RsaCryptUtil.createPrivateKey(privateKeyStr),
                             RsaCryptUtil.parseBase64Binary(token));
        return Integer.parseInt(userId) ;
    }
    @Override
    public boolean refreshToken(String token) throws Exception {
        Integer userId = verifyToken(token) ;
        if (userId > 0 ){
            String key = RedisUtil.formatUserTokenKey(userId) ;
            // 判断Token 是否过期
            String cacheToken = redisFeign.get(key) ;
            if (StringUtils.isEmpty(cacheToken)){
                return false ;
            }
            redisFeign.setTimeOut(key,token, Constant.USER_TOKEN_EXPIRE) ;
            return true ;
        }
        return false ;
    }
}

2, to provide Feignservices

@FeignClient("MOPSZ-BASIS-TOKEN")
public interface UserTokenFeign {
    /**
     * 获取 TOKEN
     */
    @PostMapping("/token/getToken")
    RespObject getToken (@RequestParam("userName") String userName,
                         @RequestParam("passWord") String passWord) ;
    /**
     * 验证 TOKEN
     */
    @PostMapping("/token/verifyToken")
    RespObject verifyToken (@RequestParam("token") String token) ;
    /**
     * 刷新 TOKEN
     */
    @PostMapping("/token/refreshToken")
    boolean refreshToken (@RequestParam("token") String token) ;
}

2, message service

  • MsgIntro

In a complex system, the notification message is a necessary module, packages typically mainly from the following two ways, message types: user messages, system messages and so on, the message receiving mode: email, SMS, and so the application side.

  • Application Process

1, the package mailing

@Service
public class SendEmailServiceImpl implements SendEmailService {
    @Override
    public void sendEmail(String receive, String title, String msg) {
        try {
            EmailUtil.sendEmail01(receive,title,msg);
        } catch (Exception e){
            e.printStackTrace() ;
            LOGGER.info("邮件发送失败:{}",e.getMessage());
        }
    }
}

2, to provide Feignservices

@FeignClient("MOPSZ-BASIS-MSGBOX")
public interface SendEmailFeign {
    /**
     * 发送Email
     */
    @PostMapping("/msgBox/sendEmail")
    void sendEmail (@RequestParam("receive") String receive,
                      @RequestParam("title") String title,
                      @RequestParam("msg") String msg) ;
}

Fifth, the source code address

GitHub·地址
https://github.com/cicadasmile/husky-spring-cloud
GitEE·地址
https://gitee.com/cicadasmile/husky-spring-cloud

Micro Services Architecture Case (04): middleware integration, public service package

Guess you like

Origin blog.51cto.com/14439672/2447789