频道栏目
首页 > 网络 > 云计算 > 正文
SpringCloud踩坑实战笔记(入门篇)
2017-07-05 11:06:08         来源:zhaoenweiex的博客  
收藏   我要投稿

SpringCloud踩坑实战笔记(入门篇)

SpringCould介绍

Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智能路由,微代理,控制总线)。简单来说,SpringCloud为开发人员提供了一系列贴有Spring品牌的适合于微服务应用开发的服务组件
本文涉及到的主要内容如下图所示。
这里写图片描述

Demo架构

这里写图片描述

主要内容

准备工作

建立开发环境,我们一共需要5个工程来完成Demo的搭建,开发环境是maven,jdk8,intellij。
目录结构如下图所示,采用maven约定的结构。
这里写图片描述

服务注册与发现(Spring Eureka)

demo-eureka工程
DemoApplication.java

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

@EnableEurekaServer
@SpringBootApplication
public class DemoApplication {

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

application.properties
ps这个配置不可用于生产环境,缺乏优化

server.port=8181#端口
spring.application.name=mmb-eureka-server#服务名称
eureka.client.register-with-eureka=false#注册自己,用于集群形式
eureka.client.fetch-registry=false#若为true的话会报错

pom.xml



    4.0.0

    com.example
    demo
    0.0.1-SNAPSHOT
    jar

    demo
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Dalston.SR1
    

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

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

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



负载均衡和连接模板(Spring Ribbon&Feign)

DemoClient2Application.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class DemoClient2Application {

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

DemoController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@RestController
public class DemoController {

    @Autowired
    private WordFeignClient wordFeignClient;

    @RequestMapping("/abc")
    public String getSentence() {
        return wordFeignClient.getWord() + wordFeignClient.getWord();
    }
}

WordFeignClient.java

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by zhaoenwei on 2017/7/1.
 */
@FeignClient("mmb-eureka-subject")
public interface WordFeignClient {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    String getWord();

}

application.properties

eureka.client.service-url.defaultZone=https://localhost:8181/eureka
server.port= 8182
spring.application.name=mmb-eureka-client2
eureka.instance.prefer-ip-address=true
mmb-eureka-subject.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

pom.xml



    4.0.0

    com.example
    demo-client2
    0.0.1-SNAPSHOT
    jar

    demo-client2
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Dalston.SR1
    

    
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-feign
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            io.springfox
            springfox-swagger2
            2.6.1
        

        
            io.springfox
            springfox-swagger-ui
            2.6.1
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

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




网关(Spring Zuul)

ZuulDemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
        import org.springframework.cloud.client.SpringCloudApplication;
        import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
        import org.springframework.context.annotation.Bean;

@SpringCloudApplication
@EnableZuulProxy

public class ZuulDemoApplication {
    @Bean
    public SimpleFilter simpleFilter() {
        return new SimpleFilter();
    }

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

SimpleFilter.java

package com.example.demo;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by zhaoenwei on 2017/6/30.
 */
public class SimpleFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(SimpleFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Map map=request.getParameterMap();
        JSONObject jsonMap= JSONObject.fromObject(map);

        log.info(String.format("%s request to %s ZEW==>params:%s", request.getMethod(), request.getRequestURL().toString(),jsonMap.toString()));

        return null;
    }

}

application.properties

#path的url是被替换掉的也示例
#zuulIP:zuulPort/sentence2/abc->serviceIP:servicePort/abc
zuul.routes.sentence.path=/sentence2/**
zuul.routes.sentence.serviceId=mmb-eureka-client2
  #zuul.routes.sentence.url=https://localhost:8182/sentence
spring.application.name=mmb-zuul-server
#下面那个参数是去掉zuul-prefix参数产生的前缀的,跟path一毛钱关系都没有

zuul.strip-prefix=false

server.port=8081
eureka.client.service-url.defaultZone=https://localhost:8181/eureka

pom.xml



    4.0.0

    com.example
    zuul-demo
    0.0.1-SNAPSHOT
    jar

    zuul-demo
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Dalston.SR1
    

    
        
            org.springframework.cloud
            spring-cloud-starter-ribbon
        
        
            org.springframework.cloud
            spring-cloud-starter-zuul
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            net.sf.json-lib
            json-lib
            2.4
            jdk15
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

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



配置中心与消息总线(Srping Config & Bus)

该配置中心设置是支持在git的统一配置管理,并支持rabbitmq的消息传播。也就是说该服务需要rabbitmq的环境。

配置中心

DemoConfigApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient
public class DemoConfigApplication {

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

application.properties

server.port=8888
spring.application.name=config-server
eureka.client.service-url.defaultZone=https://localhost:8181/eureka
eureka.instance.prefer-ip-address=true

bootstrap.properties

spring.cloud.config.server.git.uri=https://github.com/zhaoenweiex/config-repo.git
management.security.enabled=false
spring.cloud.config.server.git.basedir=target/config
spring.cloud.config.server.git.search-paths= configclient
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672

pom.xml



    4.0.0

    com.example
    demo-config
    0.0.1-SNAPSHOT
    jar

    demo-config
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Dalston.SR1
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-config-server
        
        
            org.springframework.cloud
            spring-cloud-starter
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        

        
            org.springframework.cloud
            spring-cloud-starter-bus-amqp
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

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



配置客户端

DemoConfigApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient

public class DemoClientApplication {

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

DemoController.java

package com.example.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * Created by zhaoenwei on 2017/6/29.
 */
@RefreshScope
@RestController
public class DemoController {
    private static long timeStample=System.currentTimeMillis();
//   @Autowired
//   private ConstantProperties constantProperties;

    //从config server拿到的配置数据
    @Value("${words}")
    private String wordsStr;
    @RequestMapping("/")
    public  String getWord() {
        String[] wordArray = wordsStr.split(",");
        String address= null;
        try {
            address = Inet4Address.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        int i = (int)Math.round(Math.random() * (wordArray.length - 1));
            return wordArray[i]+timeStample+ address;
    }
}

application.properties

eureka.client.service-url.defaultZone=https://192.168.31.238:8181/eureka
server.port= ${PORT:${SERVER_PORT:0}}
spring.application.name=mmb-eureka-subject
eureka.instance.prefer-ip-address=true
spring.cloud.config.uri=https://localhost:8888
spring.cloud.config.profile=dev
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672

pom.xml



    4.0.0

    com.example
    demo-client
    0.0.1-SNAPSHOT
    jar

    demo-client
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.4.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        Dalston.SR1
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        
        
            org.springframework.cloud
            spring-cloud-config-client
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.springframework.cloud
            spring-cloud-starter-bus-amqp
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

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



总结

本文展示了如何搭建基于SpringCloud的微服务框架,包括了负责服务注册于发现的Spring Eureka,负责基于客户端负载均衡的组件Srping Ribbon,负责统一配置的Spring Config,负责智能路由和网关的Sping Zuul以及消息更新的消息总线Spring Bus,还有简化Rest连接的模板Feign。
最后补充两点:
1.在springCloud中最为复杂和容易出错的的并非是业务代码开发,而是依赖与配置,所以关于.properties或.yaml都是使用SpringCloud的必背基础,
2.支撑业务的SpringBoot开发框架也是必不可少的基础知识。

 

点击复制链接 与好友分享!回本站首页
上一篇:实战spring自定义属性(schema):快速体验
下一篇:OpenVswitch源码分析之控制面关键接口与调用流程
相关文章
图文推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站