Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An overview of the introduction to SpringCloud and how to build a micro-service case for Restoration

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article gives you an overview of the introduction to SpringCloud and how to build a micro-service case for Rest. the editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.

SpringCloud 1, introduction to SpringCloud Overview 1, what is a microservice advocates dividing a single application into groups of small services. Each service runs in its own independent process. The services coordinate and cooperate with each other. Services use lightweight communication mechanisms to communicate with each other (dubbo is RPC, SpringCloud is HTTP-based restful api). Each service is built around a specific business and can be deployed to a separate production environment. (according to the business split into services, thoroughly decoupled) 2, what are the advantages and disadvantages of micro-services? And the advantages of the pit encountered in the project development: each service focuses on a specified business function and requirement decoupling between the services can be separated and flexibly matched databases in different languages: their own database + unified public database shortcomings The cost of communication between services increases the difficulty of data consistency, operation and maintenance, etc. 3. What are the services in the technology stack of microservices? springboot, spring, springmvc and other services configuration and management of Netflix's Archaius, Ali's Diamond service registration and discovery Eureka, Consul, zookeeper service invocation Rest, RPC, gRPC service fuse Hystrix (dashboard service monitoring), Envoy load balancer Ribbon, Nginx service interface calls Feign message queue kafka, RabbitMq, ActiveMq service configuration center manages SpringCloudConfig, Chef service routing Zuul service monitoring Zabbix, Nagios, Metrics, Spectator full link tracking Zipkin, Brave, Dapper service deployment Docker, Openstack, Kubernetes data flow operation development kit SpringCloud Stream (encapsulates messages sent and received with Redis\ Rabbit\ kafka, etc.) event message bus SpringCloud Bus4, What is the difference between springcloud and dubbo? Dubbo SpringCloud registry zookeeper Eureka invocation mode RPC REST API service monitoring Dubbo-monitor SpringBoot Admin Circuit Breaker-Hystrix Service Network Management Zuul distributed configuration SpringCloud config Service tracking SpringCloud Sleuth message bus SpringCloud Bus data flow SpringCloud stream batch task SpringCloud Task. . . Dubbo service governance

Official website

Https://spring.io/projects/spring-cloudhttps://springcloud.cc Chinese Community https://springcloud.cn Chinese official website

2. Build a case project of Restoration Micro Service.

Using Dept department module as a general case of micro service, Consumer consumer [client] invokes the service provided by Provider through rest.

structure

Cloud: cloud-api encapsulates the service provider of cloud-provider-dept-8001 micro-services such as overall entity, interface and public configuration, cloud-consumer-dept-80 micro-service service consumer 1, parent project

New maven project

GroupID com.leeartifact id cloudpackaging pom

POM

4.0.0 com.lee cloud 1.0-SNAPSHOT pom UTF-8 1.8 1.8 4.12 1.2.17 1.16.18 org.springframework.cloud spring-cloud-dependencies Dalston.SR1 Pom import org.springframework.boot spring-boot-dependencies 1.5.9.RELEASE pom import mysql mysql- Connector-java 5.0.4 com.alibaba druid 1.0.31 org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.0 Ch.qos.logback logback-core 1.2.3 junit junit ${junit.version} test log4j log4j ${log4j.version} 2, Cloud-api common submodule

New maven module

ModuleName cloud-apiparentProject cloudgroupId com.leeartifactId cloud-apipackaging jar

A tag will be added to the parent project POM file after the creation is completed.

POM

Cloud com.lee 1.0-SNAPSHOT 4.0.0 cloud-api org.projectlombok lombok

Entity

[micro service, be sure to implement serialization]

Package com.lee.cloud.entity;import lombok.Data;import lombok.NoArgsConstructor;import lombok.ToString;import lombok.experimental.Accessors;import java.io.Serializable;@Data@ToString@Accessors (chain = true) @ NoArgsConstructorpublic class Dept implements Serializable {private static final long serialVersionUID = 5051248965243297270L; private Long deptno; / / key private String dname; / / department name private String db_source / / from that database, because the microservice architecture can correspond to one database per service, and the same information is stored in different databases public Dept (String dname) {this.dname = dname;}} 3, cloud-provider-dept-8001 producers.

Departmental micro service provider

New maven module

ModuleName cloud--provider-dept-8001parentProject cloudgroupId com.leeartifactId cloud--provider-dept-8001packaging jar

POM

Cloud com.lee 1.0-SNAPSHOT 4.0.0 cloud--provider-dept-8001 com.lee cloud-api ${project.version} junit junit mysql mysql-connector-java Com.alibaba druid ch.qos.logback logback-core org.mybatis.spring.boot mybatis-spring-boot-starter org.springframework.boot spring-boot-starter-jetty org.springframework .boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test org.springframework springloaded org.springframework.boot spring-boot-devtools true

Application.yml

Server: port: 8001mybatis: config-location: classpath:mybatis/mybatis.cfg.xml # mybatis configuration file path type-aliases-package: com.lee.cloud.entity # all Entity alias classes package mapper-locations:-classpath:mybatis/mapper/**/*.xml # mapper mapping file spring: application: name: cloud-dept datasource: type: Com.alibaba.druid.pool.DruidDataSource # current data source operation type driver-class-name: org.gjt.mm.mysql.Driver # mysql driver package url: jdbc:mysql://localhost:3306/cloudDB01 # Database name username: root password: 123456 dbcp2: min-idle: 5 # minimum number of maintained connections for database connection pool initial-size: 5 # initialization connections max-total: 5 # maximum number of connections max-wait-millis: 200 # Maximum timeout for waiting for a connection to be acquired

Mybatis.cfg.xml

Mysql

DROP DATABASE IF EXISTS cloudDB01;CREATE DATABASE cloudDB01 CHARACTER SET UTF8;USE cloudDB01;CREATE TABLE dept (deptno BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT, dname VARCHAR (60), db_source VARCHAR (60)); INSERT INTO dept (dname,db_source) VALUES ('Development Department', DATABASE ()); INSERT INTO dept (dname,db_source) VALUES ('personnel Department', DATABASE ()); INSERT INTO dept (dname,db_source) VALUES ('Finance Department', DATABASE ()) INSERT INTO dept (dname,db_source) VALUES ('Marketing Department', DATABASE ()); INSERT INTO dept (dname,db_source) VALUES ('Operation and maintenance Department', DATABASE ()); SELECT * FROM dept

Interface: dao\ mapper\ service\ controller\

DAO:package com.lee.cloud.dao;import com.lee.cloud.entity.Dept;import org.apache.ibatis.annotations.Mapper;import java.util.List;/** * springboot integrate mybatis * the first method: add @ Mapper * to dao the second method: add @ MapperScan * / @ Mapperpublic interface DeptDao {public boolean addDept (Dept dept); public Dept findById (Long id); public List findAll () }-MAPPER select deptno,dname,db_source from dept where deptno=# {deptno}; select deptno,dname,db_source from dept INSERT INTO dept (dname,db_source) VALUES (# {dname}, DATABASE ());-SERVICE package com.lee.cloud.service;import com.lee.cloud.entity.Dept Import java.util.List;public interface DeptService {public boolean add (Dept dept); public Dept get (Long id); public List list () }-SERVICE IMPL package com.lee.cloud.service.impl;import com.lee.cloud.dao.DeptDao;import com.lee.cloud.entity.Dept;import com.lee.cloud.service.DeptService Import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class DeptServiceImpl implements DeptService {@ Autowired private DeptDao dao; @ Override public boolean add (Dept dept) {return dao.addDept (dept);} @ Override public Dept get (Long id) {return dao.findById (id);} @ Override public List list () {return dao.findAll () }-CONTROLLER package com.lee.cloud.controller;import com.lee.cloud.entity.Dept;import com.lee.cloud.service.DeptService;import org.springframework.beans.factory.annotation.Autowired Import org.springframework.web.bind.annotation.*;import java.util.List;@RestControllerpublic class DeptController {@ Autowired private DeptService service; @ RequestMapping (value= "/ dept/add", method= RequestMethod.POST) public boolean add (@ RequestBody Dept dept) {return service.add (dept) @ RequestMapping (value= "/ dept/get/ {id}", method=RequestMethod.GET) public Dept get (@ PathVariable ("id") Long id) {return service.get (id);} @ RequestMapping (value= "/ dept/list", method=RequestMethod.GET) public List list () {return service.list ();}}

Main startup class APP

Package com.lee.cloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class DeptProvider8001_APP {public static void main (String [] args) {SpringApplication.run (DeptProvider8001_APP.class,args);}}

Test:

Http://localhost:8001/dept/list results: [{"deptno": 1, "dname": "Development Department", "db_source": "clouddb01"}, {"deptno": 2, "dname": "personnel Department", "db_source": "clouddb01"}, {"deptno": 3, "dname": "Finance Department", "db_source": "clouddb01"}, {"deptno": 4, "dname": "Marketing Department", "db_source": "clouddb01"} {"deptno": 5, "dname": "Operation and maintenance Department", "db_source": "clouddb01"}] 3, cloud-consumer-dept-80 consumers

Departmental micro-service consumers

New maven module

ModuleName cloud--consumer-dept-80parentProject cloudgroupId com.leeartifactId cloud--consumer-dept-80packaging jar

POM

Cloud com.lee 1.0-SNAPSHOT 4.0.0 cloud-consumer-dept-80 department micro service consumer com.lee cloud-api ${project.version} org.springframework.boot spring-boot-starter-web Org.springframework springloaded org.springframework.boot spring-boot-devtools

APPLICATION.YML

Server: port: 80

ConfigBean configuration class

Package com.lee.cloud.cfgbean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.client.RestTemplate / / configuration class @ Configurationpublic class ConfigBean {/ / RestTemplate provides a variety of convenient methods to access remote HTTP services / / is a simple and convenient restful service template class, which is a client template toolset provided by spring for accessing Rest services / / such as JDBCTemplate RedisTemplate @ Bean public RestTemplate restTemplate () {return new RestTemplate ();}}

RestTemplate provides a variety of convenient ways to access remote HTTP services

Is a simple and convenient template class for accessing restful services. It is a client template toolset provided by spring for accessing Rest services.

Similar to JDBCTemplate RedisTemplate etc.

Controller

Package com.lee.cloud.controller;import com.lee.cloud.entity.Dept;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;import java.util.List;@RestControllerpublic class DeptController_Consumer {private static final String REST_URL_PREFIX = "http://localhost:8001"; @ Autowired private RestTemplate restTemplate" @ RequestMapping (value= "/ consumer/dept/add") public boolean add (Dept dept) {return restTemplate.postForObject (REST_URL_PREFIX+ "/ dept/add", dept, Boolean.class);} @ RequestMapping (value= "/ consumer/dept/get/ {id}") public Dept get (@ PathVariable ("id") Long id) {return restTemplate.getForObject (REST_URL_PREFIX+ "/ dept/get/" + id, Dept.class) @ RequestMapping (value= "/ consumer/dept/list") public List list () {return restTemplate.getForObject (REST_URL_PREFIX+ "/ dept/list", List.class);}}

Startup class:

Package com.lee.cloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class DeptConsumer80_App {public static void main (String [] args) {SpringApplication.run (DeptConsumer80_App.class,args);}}

Test:

1. Start the provider service and then start the consumer service 2, http://localhost/consumer/dept/list3, http://localhost/consumer/dept/get/14, and http://localhost/consumer/dept/add?dname=. The above is an overview of SpringCloud and how to build a micro-service case for Rest. the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report