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

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

【微服务架构】springcloud微服务架构搭建_第1张图片

微服务架构的应用场景:

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

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

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

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

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

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

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

Spring Cloud的优势

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

项目架构:

【微服务架构】springcloud微服务架构搭建_第2张图片

一、discovery服务注册发现

①、pom.xml



	4.0.0
	
		com.gt
		popuserver
		0.0.1-SNAPSHOT
	


	discovery
	discovery
	http://www.popumusic

	
		com.wisely.discovery.DiscoveryApplication
	

	
		
			org.springframework.cloud
			spring-cloud-starter-eureka-server
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	




②、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



	4.0.0
	
		com.gt
		popuserver
		0.0.1-SNAPSHOT
	
	com.poputar
	popumonitor
	0.0.1-SNAPSHOT
	popumonitor
	http://maven.apache.org
	
		UTF-8
	
	
		
			org.springframework.cloud
			spring-cloud-starter
			1.1.7.RELEASE
		
		
			org.springframework.cloud
			spring-cloud-starter-hystrix-dashboard
			1.2.2.RELEASE
		
		
			org.springframework.cloud
			spring-cloud-starter-turbine
			1.1.7.RELEASE
		
		
			junit
			junit
			3.8.1
			test
		
	
	
		
			
				com.spotify
				docker-maven-plugin
				
					${project.name}:${project.version}
					${project.basedir}/src/main/docker
					false
					
						
							${project.build.directory}
							${project.build.finalName}.jar
						
					
				
			
		
	


②、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



	4.0.0
	
		com.gt
		popuserver
		0.0.1-SNAPSHOT
	
	com.poputar
	popuconfig
	0.0.1-SNAPSHOT
	popuconfig
	http://maven.apache.org
	
		UTF-8
	
	
		
			org.springframework.cloud
			spring-cloud-starter
			1.1.7.RELEASE
		
		
			org.springframework.cloud
			spring-cloud-config-server
			1.2.2.RELEASE
		
		
			org.springframework.cloud
			spring-cloud-starter-eureka
			1.1.7.RELEASE
		
		
			junit
			junit
			3.8.1
			test
		
	
	
		
			
				com.spotify
				docker-maven-plugin
				
					${project.name}:${project.version}
					${project.basedir}/src/main/docker
					false
					
						
							${project.build.directory}
							${project.build.finalName}.jar
						
					
				
			
		
	


②、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微服务架构搭建_第3张图片


四、用户服务

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



	4.0.0
	
		com.gt
		popuserver
		0.0.1-SNAPSHOT
	
	popuman
	popuman
	http://www.popumusic

	
		
			org.springframework.boot
			spring-boot-starter-data-redis
		
		
			org.springframework.cloud
			spring-cloud-starter-eureka
		
		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
			mysql
			mysql-connector-java
		
		
			org.springframework.cloud
			spring-cloud-starter-config
		
		
		
			aliyun-java-sdk-dysmsapit
			aliyun-java-sdk-dysmsapi
			1.0.0
			system
			${project.basedir}/lib/aliyun-java-sdk-dysmsapi-1.0.0.jar
		
		
		
			aliyun-java-sdk-core
			aliyun-java-sdk-core
			3.3.1
			system
			${project.basedir}/lib/aliyun-java-sdk-core-3.3.1.jar
		

	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
		
		
		
	


②、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;  
    }  
}

⑤、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级别日志输出到各自的日志文件

    
        
        
            
            %d %p (%file:%line\)- %m%n  
            UTF-8   
            
        
          
        /Users/david/Documents/Poputar/logs/popuman.log    
            
            /Users/david/Documents/Poputar/logs/popuman.%d.%i    
                
                    
                64 MB    
                
            
            
                
                %d %p (%file:%line\)- %m%n  
                
            UTF-8    
         
         
		    ERROR  
		    DENY  
		    ACCEPT  
		   
        
        
        /Users/david/Documents/Poputar/logs/popuman_err.log    
            
            /Users/david/Documents/Poputar/logs/popuman_err.%d.%i    
                
                    
                64 MB    
                
            
            
                
                %d %p (%file:%line\)- %m%n  
                
            UTF-8    
        
		
			ERROR
			ACCEPT
			DENY
		     
        
        
            
    
    
        
            
            
        

五、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















你可能感兴趣的:(java,springboot,springcloud)