Spring Cloud:Eureka服務發現

Eureka的服務註冊和服務發現是一塊兒的,服務發現是一個服務,將本身暴露給Eureka的服務註冊,這樣別人就能夠經過Eureka調用服務了。Eureka服務註冊自己是也個服務,也能夠配置集羣。
Eureka服務註冊發現
Eureka的服務註冊會在集羣中同步服務發現的數據,保證服務高可用。經過Feign,Ribbon等方式能夠調用服務註冊暴露的服務,Feign和Ribbon都是客戶端的LB(負載均衡),實際使用中,可加一層網關Zuul,Zuul網關也能夠作集羣,在網關之上能夠配置服務端的LB。html

這裏作一個二維碼的微服務,來講明Eureka服務發現。java

Eureka服務發現,須要引入spring-cloud-starter-eureka
springfox-swagger2是一套在線Rest API文檔
zxing是用於二維碼的生成和解析的git

//build.gradle
group 'org.sauceggplant'
version '0.0.1-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'spring-boot'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    maven{url 'http://192.168.56.103:8081/repository/zhaozx/'}
}

dependencies {
    compile 'org.springframework.cloud:spring-cloud-starter-config:1.3.1.RELEASE'
    compile 'org.springframework.cloud:spring-cloud-starter-eureka:1.3.1.RELEASE'
    compile 'org.springframework.boot:spring-boot-actuator:1.5.3.RELEASE'
    compile 'io.springfox:springfox-swagger2:2.7.0'
    compile 'io.springfox:springfox-swagger-ui:2.7.0'
    compile 'com.google.zxing:core:3.3.0'
    compile 'com.google.zxing:javase:3.3.0'
    testCompile 'org.springframework.boot:spring-boot-starter-test:1.5.3.RELEASE'
}

buildscript {
    repositories {
        maven{url 'http://192.168.56.103:8081/repository/zhaozx/'}
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.3.RELEASE'
    }
}

jar {
    baseName = 'QRCode'
    version =  '0.0.1-SNAPSHOT'
}

啓動類中配置@EnableEurekaClient啓動Eureka的服務發現web

//QRCodeApplication.java
package org.sauceggplant.qrcode;

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

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

二維碼服務的Controller,與SpringMVC的Controller沒什麼區別。
@RestController聲明一個restful風格的Controller
@RequestMapping表示請求的路徑
@ApiOperation是swagger2的註解,加上註解後能夠生成在線swagger文檔
@RequestParam是請求的參數(@RequestBody請求體)
@ResponseBody是返回的內容spring

//QRCodeController.java
package org.sauceggplant.qrcode.controller;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.HybridBinarizer;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/qrcode")
public class QRCodeController {

    private static BASE64Decoder decoder = new BASE64Decoder();

    private static BASE64Encoder encoder = new BASE64Encoder();

    @ApiOperation(value = "獲取二維碼圖片",notes = "獲取二維碼圖片",produces="image/*")
    @RequestMapping(value = "/image", method = RequestMethod.GET, produces="image/*")
    public void getQRCode(HttpServletResponse response, @RequestParam int width,@RequestParam int height,@RequestParam String format,@RequestParam String content) {
        try {
            width=width==0?200:width;
            height=height==0?200:height;
            format=format==null?"png":format;
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content==null?"NULL":content,BarcodeFormat.QR_CODE, width, height, hints);
            OutputStream outputStream = (OutputStream)response.getOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix,format,outputStream);
            if(outputStream!=null){
                outputStream.close();
            }
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "獲取二維碼信息",notes = "獲取二維碼信息")
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> getQRCodeString(@RequestParam int width,@RequestParam int height,@RequestParam String format,@RequestParam String content) {
        try {
            width=width==0?200:width;
            height=height==0?200:height;
            format=format==null?"png":format;
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content==null?"NULL":content,BarcodeFormat.QR_CODE, width, height, hints);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix,format,byteArrayOutputStream);
            String data = encoder.encode(byteArrayOutputStream.toByteArray());
            return new ResponseEntity(data,HttpStatus.OK);
        } catch (WriterException e) {
            e.printStackTrace();
            return new ResponseEntity(null, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ApiOperation(value = "獲取二維碼信息",notes = "獲取二維碼信息")
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> postQRCode(@RequestBody(required = true) String content) {
        try {
            byte[] data = decoder.decodeBuffer(content);
            BufferedImage image;
            ByteArrayInputStream in = new ByteArrayInputStream(data);
            image = ImageIO.read(in);
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);
            return new ResponseEntity(result.getText(), HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity(null, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (NotFoundException e) {
            e.printStackTrace();
            return new ResponseEntity(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

Swagger2配置bootstrap

//SwaggerConfiguration.java
package org.sauceggplant.qrcode.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("二維碼微服務")
                        .description("二維碼生成,解析")
                        .version("0.0.1-SNAPSHOT")
                        .build())
                .select()
                .apis(RequestHandlerSelectors.basePackage("org.sauceggplant.qrcode.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

application.ymlapi

#application.yml
server:
  port: 8762
spring:
  application:
    name: QRCode
#  cloud:
#    config:
#      server:
#        git:
#         url: http://192.168.56.101/zhaozx/config-repo/qrcode
#  profiles:
#    active: dev
eureka:
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:8761/eureka/  #Eureka服務註冊成地址

bootstrap.ymlrestful

#bootstrap.yml
eureka:
  instance:
    lease-renewal-interval-in-seconds: 10     # 心跳時間,即服務續約間隔時間(缺省爲30s)
    lease-expiration-duration-in-seconds: 60  # 發呆時間,即服務續約到期時間(缺省爲90s)
  client:
    healthcheck:
      enabled: true

http://127.0.0.1:8762/swagger...app

Swagger

相關文章
相關標籤/搜索