【微服务架构】springcloud微服务架构搭建

时间:2021-06-24 15:04:52

要会用,首先要了解。图懒得画,借鉴网上大牛的图吧,springcloud组建架构如图:

【微服务架构】springcloud微服务架构搭建【微服务架构】springcloud微服务架构搭建【微服务架构】springcloud微服务架构搭建

微服务架构的应用场景:

1、系统拆分,多个子系统

2、每个子系统可部署多个应用,应用之间负载均衡实现

3、需要一个服务注册中心,所有的服务都在注册中心注册,负载均衡也是通过在注册中心注册的服务来使用一定策略来实现。

4、所有的客户端都通过同一个网关地址访问后台的服务,通过路由配置,网关来判断一个URL请求由哪个服务处理。请求转发到服务上的时候也使用负载均衡。

5、服务之间有时候也需要相互访问。例如有一个用户模块,其他服务在处理一些业务的时候,要获取用户服务的用户数据。

6、需要一个断路器,及时处理服务调用时的超时和错误,防止由于其中一个服务的问题而导致整体系统的瘫痪。

7、还需要一个监控功能,监控每个服务调用花费的时间等。

Spring Cloud的优势

  • 产出于spring大家族,spring在企业级开发框架中无人能敌,来头很大,可以保证后续的更新、完善。比如dubbo现在就差不多死了
  • 有spring Boot 这个独立干将可以省很多事,大大小小的活spring boot都搞的挺不错。
  • 作为一个微服务治理的大家伙,考虑的很全面,几乎服务治理的方方面面都考虑到了,方便开发开箱即用。
  • Spring Cloud 活跃度很高,教程很丰富,遇到问题很容易找到解决方案
  • 轻轻松松几行代码就完成了熔断、均衡负责、服务中心的各种平台功能
废话少说,看代码:

项目架构:

【微服务架构】springcloud微服务架构搭建

一、discovery服务注册发现

①、pom.xml

<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.gt</groupId>
<artifactId>popuserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>


<artifactId>discovery</artifactId>
<name>discovery</name>
<url>http://www.popumusic</url>

<properties>
<start-class>com.wisely.discovery.DiscoveryApplication</start-class>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>

②、DiscoveryApplication

package com.wisely.discovery;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer //1
public class DiscoveryApplication {

public static void main(String[] args) {
SpringApplication.run(DiscoveryApplication.class, args);
}

}

③、application.yml

server:
port: 8761

endpoints:
shutdown:
enabled: true
sensitive: false
eureka:
instance:
prefer-ip-address: true #启用IP方式
ip-address: 127.0.0.1
client:
register-with-eureka: false #指向其他注册中心地址
fetch-registry: false
service-url:
defualtZone: http://127.0.0.1:8762/eureka/

二、monitor监控服务

①、pom.xml

<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.gt</groupId>
<artifactId>popuserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.poputar</groupId>
<artifactId>popumonitor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>popumonitor</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
<version>1.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-turbine</artifactId>
<version>1.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<configuration>
<imageName>${project.name}:${project.version}</imageName>
<dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
<skipDockerBuild>false</skipDockerBuild>
<resources>
<resource>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
</plugins>
</build>
</project>

②、PopumonitorApplication

package com.poputar;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine;

/**
* 监控服务
*
*/
@SpringBootApplication
@EnableEurekaClient
@EnableHystrixDashboard
@EnableTurbine
public class PopumonitorApplication
{
public static void main( String[] args )
{
SpringApplication.run(PopumonitorApplication.class, args);
}
}

③、application.yml

server:
port: 8989


④、bootstrap.yml

spring:
application:
name: monitor

eureka:
instance:
nonSecurePort: ${server.port:8989}
client:
serviceUrl:
defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/


三、配置服务

①、pom.xml

<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.gt</groupId>
<artifactId>popuserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.poputar</groupId>
<artifactId>popuconfig</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>popuconfig</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
<version>1.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<configuration>
<imageName>${project.name}:${project.version}</imageName>
<dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
<skipDockerBuild>false</skipDockerBuild>
<resources>
<resource>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
</plugins>
</build>
</project>


②、PopuconfigApplication

package org.popuconfig;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
* 配置服务
*
*/
@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class PopuconfigApplication
{
public static void main( String[] args )
{
SpringApplication.run(PopuconfigApplication.class, args);
}
}

③、application.yml 配置文件放本地,读者可以自己研究下放在git服务上

spring:
cloud:
config:
server:
native:
search-locations: classpath:/config

server:
port: 8762

④、bootstrap.yml

spring:
application:
name: config #1
profiles:
active: native #2

eureka:
instance:
non-secure-port: ${server.port:8762} #3
metadata-map:
instanceId: ${spring.application.name}
client:
service-url:
defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/ #5


⑤、src/main/resources/config下放应用所需的配置文件,命名方式跟appname相同,切记此处的命名是有规范的

【微服务架构】springcloud微服务架构搭建

【微服务架构】springcloud微服务架构搭建

四、用户服务

①、pom.xml 需要引入外部jar包时,我已做注释,如下:

<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.gt</groupId>
<artifactId>popuserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>popuman</artifactId>
<name>popuman</name>
<url>http://www.popumusic</url>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>

<dependency>
<groupId>aliyun-java-sdk-dysmsapit</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/aliyun-java-sdk-dysmsapi-1.0.0.jar</systemPath>
</dependency>

<dependency>
<groupId>aliyun-java-sdk-core</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.3.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/aliyun-java-sdk-core-3.3.1.jar</systemPath>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>

<!-- 将外部包打入jar docker部署时需要打开,否则报错,找不到jar -->
<!-- <resources>
<resource>
<directory>lib</directory>
<targetPath>BOOT-INF/lib/</targetPath>
<includes>
<include>**/*.jar</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<targetPath>BOOT-INF/classes/</targetPath>
</resource>
</resources> -->
</build>
</project>

②、PopumanApplication 增加了国际化配置

package com.gt;

import javax.validation.Validator;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@SpringBootApplication
@EnableEurekaClient
public class PopumanApplication {
public static void main(String[] args) {
SpringApplication.run(PopumanApplication.class, args);
}

public ResourceBundleMessageSource getMessageSource() throws Exception {
ResourceBundleMessageSource rbms = new ResourceBundleMessageSource();
rbms.setDefaultEncoding("UTF-8");
rbms.setBasenames("i18n/ValidationMessages");
return rbms;
}

@Bean
public Validator getValidator() throws Exception {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(getMessageSource());
return validator;
}
}

③、LocaleConfig 拦截器
package com.gt;import java.util.Locale;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.LocaleResolver;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;import org.springframework.web.servlet.i18n.SessionLocaleResolver;@Configuration@EnableAutoConfiguration@ComponentScan	public class LocaleConfig extends WebMvcConfigurerAdapter {	@Bean    public LocaleResolver localeResolver() {        SessionLocaleResolver slr = new SessionLocaleResolver();        // 默认语言        slr.setDefaultLocale(Locale.US);        return slr;    }    @Bean    public LocaleChangeInterceptor localeChangeInterceptor() {        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();        // 参数名        lci.setParamName("lang");        return lci;    }        @Override    public void addInterceptors(InterceptorRegistry registry) {        registry.addInterceptor(localeChangeInterceptor());    }	}

④、MessageManager 读取国际化文件内容

package com.gt;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

@Component
public class MessageManager {

private static MessageSource messageSource;

public static String getMsg(String key) {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage(key, null, locale);
}

public static String getMsg(String key, String... arg) {
Locale locale = LocaleContextHolder.getLocale();
Object[] args = new Object[arg.length];
for (int i = 0; i < arg.length; i++) {
args[i] = arg[i];
}
return messageSource.getMessage(key, args, locale);
}

@Autowired(required = true)
public void setMessageSource(MessageSource messageSource) {
MessageManager.messageSource = messageSource;
}
}
【微服务架构】springcloud微服务架构搭建

⑤、application.yml

debug: true
server:
port: 8781

⑥、bootstrap.yml docker环境下部署时需要指定ip,否则找不到配置服务,读取不了配置中心的相关配置

spring:
application:
name: popuman
cloud:
config:
enabled: true
discovery: #配置服务发现,获取配置信息 配置文件命名要按照springcloud config配置文件命名规则命名
enabled: true
service-id: config
eureka:
instance:
appname: popuman
client:
service-url:
defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/

#docker环境下需指定ip才能访问
#eureka:
# instance:
# appname: popuman
# prefer-ip-address: true #启用IP方式
# ip-address: 192.168.*.**
# client:
# service-url:
# defaultZone: http://192.168.*.**:8761/eureka/

⑦、logback.xml 日志分级别输出到文件,dubug,error级别日志输出到各自的日志文件

<configuration>    
<!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %p (%file:%line\)- %m%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="popuman"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>/Users/david/Documents/Poputar/logs/popuman.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>/Users/david/Documents/Poputar/logs/popuman.%d.%i</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 64 MB -->
<maxFileSize>64 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>
%d %p (%file:%line\)- %m%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter"> <!-- 过滤错误日志 -->
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
</appender>
<appender name="popuman_err"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>/Users/david/Documents/Poputar/logs/popuman_err.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>/Users/david/Documents/Poputar/logs/popuman_err.%d.%i</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 64 MB -->
<maxFileSize>64 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<pattern>
%d %p (%file:%line\)- %m%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter"><!-- 只打印错误日志 -->
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
<!-- 输出日志 -->
<logger name="com.gt" level="DEBUG">
<appender-ref ref="popuman" />
<appender-ref ref="popuman_err" />
</logger>
</configuration>

五、popumusic项目代码就不贴了,同popuman项目类似。

部署到docker时,切记端口映射好,否则调不通。

六、应用之间服务的调用是通过springcloud的FeignClient调用,这种调用方式同样也是基于http协议,好处是不用我们再去封装httpclient手写post,get请求,通过调用方法的方式就可以调用其他服务接口

本架构采用springboot推荐的JPA方式来处理数据层,缓存采用redis,如果您要问,redis挂掉怎么办?那就要考虑redis的分布式,主从等,这里不做赘述。

spriingcloud是近两年新兴的微服务技术,目前我也是在学习中,如有觉得我写的有不对的地方,还请批评指正,共同交流,学习一门新技术是枯燥的,难免走很多弯路,但是当你突破难关时,那样的轻松是何等畅快!在这里也感谢CSDN上大牛的技术文章分享,有分享才会有进步。希望本文对学习springcloud的同学有所帮助。


推荐几篇springcloud总结比较全的博客,也是本文项目搭建过程借鉴的技术文章

方志鹏大牛博客地址:http://blog.csdn.net/forezp/article/category/6830968/1

司青博客:http://blog.csdn.net/neosmith/article/details/52449921

http://blog.csdn.net/f1576813783/article/details/76805195


方志鹏http://blog.csdn.net/forezp/article/category/68