java 微服务框架 demo_微服务框架之SpringBoot

本文介绍了SpringBoot的基础知识,包括其目的、特性,并详细展示了如何创建一个SpringBoot项目,从配置文件修改到单元测试,再到自定义Banner,以及如何进行消息队列的整合,包括使用内嵌和外部服务。
摘要由CSDN通过智能技术生成

1. 什么是SpringBoot

Spring Boot 是 Spring 社区较新的一个项目。该项目的目的是帮助开发者更容易的创建基于 Spring 的应用程序和服务,让更多人的人更快的对 Spring 进行入门体验,为 Spring 生态系统提供了一种固定的、约定优于配置风格的框架。

Spring Boot 具有如下特性:

(1)为基于 Spring 的开发提供更快的入门体验

(2)开箱即用,没有代码生成,也无需 XML 配置。同时也可以修改默认值来满足特定的需求。

(3)提供了一些大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等。

(4)Spring Boot 并不是不对 Spring 功能上的增强,而是提供了一种快速使用 Spring 的方式。

2. SpringBoot基础操作

2.1. SpringBoot入门工程

使用 Intellij IDEA 来新建一个 Spring Boot 项目,打开 IDEA -> New Project -> Spring Initializr。

97788fbb24c6

image.png

填写项目信息:

97788fbb24c6

image.png

选择 Spring Boot 版本及 Web 开发所需的依赖

97788fbb24c6

image.png

创建完成后的工程目录结构如下:

.gitignore:Git 过滤配置文件

pom.xml:Maven 的依赖管理配置文件

SpringbootdemoApplication.java:程序入口

resources:资源文件目录

static: 静态资源文件目录

templates:模板资源文件目录

application.properties:Spring Boot 的配置文件,实际开发中会替换成 YAML 语言配置(application.yml)

pom.xml

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.2.7.RELEASE

com.demon

springbootdemo

0.0.1-SNAPSHOT

springbootdemo

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.springframework.boot

spring-boot-maven-plugin

parent:继承了 Spring Boot 的 Parent,表示我们是一个 Spring Boot 工程

spring-boot-starter-web:包含了 spring-boot-starter 还自动帮我们开启了 Web 支持

功能演示

创建一个 Controller 来演示一下 Spring Boot

package com.funtl.hello.spring.boot.controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class HelloController {

@RequestMapping(value = "", method = RequestMethod.GET)

public String sayHi() {

return "Hello Spring Boot";

}

}

启动 SpringbootdemoApplication 的 main() 方法,浏览器访问 http://localhost:8080 可以看到:

Hello Spring Boot

2.2. 单元测试

主要是通过 @RunWith 和 @SpringBootTest 注解来开启单元测试功能

package com.funtl.hello.spring.boot;

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.boot.test.web.client.TestRestTemplate;

import org.springframework.boot.web.server.LocalServerPort;

import org.springframework.http.ResponseEntity;

import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;

import static org.hamcrest.CoreMatchers.equalTo;

import static org.junit.Assert.assertThat;

@RunWith(SpringRunner.class)

@SpringBootTest(classes = HelloSpringBootApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

public class HelloSpringBootApplicationTests {

@LocalServerPort

private int port;

private URL base;

@Autowired

private TestRestTemplate template;

@Before

public void setUp() throws Exception {

this.base = new URL("http://localhost:" + port + "/");

}

@Test

public void contextLoads() {

ResponseEntity response = template.getForEntity(base.toString(), String.class);

assertThat(response.getBody(), equalTo("Hello Spring Boot"));

}

}

运行它会先启动 Spring Boot 工程,再启动单元测试

2.3. 常用配置

2.3.1. 修改tomcat启动端口

在src/main/resources下修改application.properties或者application.yml文件

#application.yml修改如下

server:

port: 9090

#application.properties修改如下

server.port=8088

重新运行引导类,输入访问地址进行访问。

2.3.2. 读取配置文件信息

在src/main/resources下的application.properties 增加配置

info=这是一个测试文本

在类中读取这个配置信息,修改HelloWorldController

@Autowired

private Environment env;

@RequestMapping("/info")

public String info(){

return "HelloWorld~~"+env.getProperty("info");

}

2.3.3 热部署

在开发中反复修改类、页面等资源,每次修改后都是需要重新启动才生效,这样每次启动都很麻烦,浪费了大量的时间,能不能在修改代码后不重启就能生效呢?可以,在pom.xml中添加如下配置就可以实现这样的功能,这个过程称之为热部署。

org.springframework.boot

spring-boot-devtools

2.3.4 自定义 Banner

在 Spring Boot 启动的时候会有一个默认的启动图案

. ____ _ __ _ _

/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

\\/ ___)| |_)| | | | | || (_| | ) ) ) )

' |____| .__|_| |_|_| |_\__, | / / / /

=========|_|==============|___/=/_/_/_/

:: Spring Boot :: (v2.2.7.RELEASE)

在 src/main/resources 目录下新建一个 banner.txt

通过 http://patorjk.com/software/taag 网站生成字符串,将网站生成的字符复制到 banner.txt 中

再次运行这个程序

${AnsiColor.BRIGHT_RED}

// _ooOoo_ //

// o8888888o //

// 88" . "88 //

// (| ^_^ |) //

// O\ = /O //

// ____/`---'\____ //

// .' \\| |// `. //

// / \\||| : |||// \ //

// / _||||| -:- |||||- \ //

// | | \\\ - /// | | //

// | \_| ''\---/'' | | //

// \ .-\__ `-` ___/-. / //

// ___`. .' /--.--\ `. . ___ //

// ."" '< `.___\__/___.' >'"". //

// | | : `- \`.;`\ _ /`;.`/ - ` : | | //

// \ \ `-. \_ __\ /__ _/ .-` / / //

// ========`-.____`-.___\_____/___.-`____.-'======== //

// `=---=' //

// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //

// 佛祖保佑 永不宕机 永无BUG //

常用属性设置:

${AnsiColor.BRIGHT_RED}:设置控制台中输出内容的颜色

${application.version}:用来获取 MANIFEST.MF 文件中的版本号

${application.formatted-version}:格式化后的 ${application.version} 版本信息

${spring-boot.version}:Spring Boot 的版本号

${spring-boot.formatted-version}:格式化后的 ${spring-boot.version} 版本信息

2.3.5 关闭特定的自动配置

关闭特定的自动配置使用 @SpringBootApplication 注解的 exclude 参数即可,这里以关闭数据源的自动配置为例

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

3. SpringBoot相关服务整合

3.1. 使用内嵌服务

(1)在pom.xml中引入ActiveMQ起步依赖

org.springframework.boot

spring-boot-starter-activemq

(2)创建消息生产者

/**

* 消息生产者

* @author Administrator

*/

@RestController

public class QueueController {

@Autowired

private JmsMessagingTemplate jmsMessagingTemplate;

@RequestMapping("/send")

public void send(String text){

jmsMessagingTemplate.convertAndSend("springBoot_text", text);

}

}

(3)创建消息消费者

@Component

public class Consumer {

@JmsListener(destination="springBoot_text")

public void readMessage(String text){

System.out.println("接收到消息:"+text);

}

}

测试:启动服务后,在浏览器执行:localhost:8088/send.do?text=aaaaa

即可看到控制台输出消息提示。Spring Boot内置了ActiveMQ的服务,所以不用单独启动也可以执行应用程序。

3.2. 使用外部服务

在src/main/resources下的application.properties增加配置, 指定ActiveMQ的地址

spring.activemq.broker-url=tcp://192.168.25.129:61616

3.3. 发送Map信息

(1)修改QueueController.java

@RequestMapping("/sendmap")

public void sendMap(){

Map map=new HashMap<>();

map.put("mobile", "13900001111");

map.put("content", "恭喜获得10元代金券");

jmsMessagingTemplate.convertAndSend("springBoot_map",map);

}

(2)修改Consumer.java

@JmsListener(destination="springBoot_map")

public void readMap(Map map){

System.out.println(map);

}

文档下载地址:

demo参考网上资料,使用mvn建项,使用者需要有一定mvn基础。 demo没有实现复杂业务,只实现了部分功能: 微服务模块初始化时,常量和数据库信息等使用云配置服务(spring config)获取; 微服务之间使用负载均衡(ribbon); 微服务网关路由配置; 微服务断路器(hystrix)及监听服务等 启动步骤: 1.启动server-eureka,端口6600,微服务注册中心 访问http://localhost:6600,查看效果 2.启动server-config,端口6700,统一配置服务中心 访问http://localhost:6700/service-order/online,查看效果 3.启动service-order,端口6002,初始化使用配置服务server-config动态加载数据库 访问http://localhost:6002/order,查看效果 4.启动service-user,端口6001,使用注册后的服务名service-order进行服务之间调用,避免传统维护困难的ip:port方式 模块中使用了ribbon负载均衡请求service-order,需要启动至少两个service-order服务 访问http://localhost:6001/user/order,查看效果 5.启动gateway-zuul,端口6000,用于url路由配置,服务统一端口入口 http://localhost:6000/service-order/order等效于访问http://localhost:6002/order http://localhost:6000/service-user/user/order等效于访问http://localhost:6001/user/order 6.启动hystrix-dashboard,端口6500,可选,WEB界面查看监听服务,如服务成功多少,失败多少等信息 进入hystrix-dashboard界面后,填入监控地址:http://localhost:6001/hystrix.stream
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值