您的位置:首页 > 编程语言 > Java开发

Spring Cloud搭建微服务架构----使用Spring boot开发web项目

2017-04-19 00:00 666 查看
摘要: Spring生态是java web开发的最强大的生态,借助SpringBoot可以忽略之前使用SpringMVC时的配置过程,以一个更简单的方式去构建一个web应用,将更多的时间投入到业务处理中去。

项目服务实例之间主要通过RestAPI方式进行通信,所以服务本身可借助SpringBoot快速开发Restful web API。

开发Restful web服务

以 http get方式访问:http://localhost:8080/hello

获取响应:{"id":1,"content":"Hello, World!"}

使用工具:

IDEA;

Mven3;

实体类

Hello.java

package hello;

public class Hello{

private final long id;
private final String content;

public Hello(long id, String content) {
this.id = id;
this.content = content;
}

public long getId() {
return id;
}

public String getContent() {
return content;
}
}

构建Controller

通过注解@RestController 声明一个Restful接口。

HelloController.java

@RestController
public class HelloController {

private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();

@RequestMapping("/hello")
public Hellohello(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}

入口Main文件

由于SpringBoot可以方便的通过jar文件进行交付,通过Main入口文件的配置可以启动一个内置的tomcat进行服务实例运行。

@SpringBootApplication
public class Application {

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

至此一个简单的Restful风格api构建成功,没有springmvc的xml文件需要配置,非常方便。

maven打包,执行jar包:

java -jar build/libs/gs-rest-service-0.1.0.jar

访问http请求:

http://localhost:8080/greeting

响应结果:

{"id":1,"content":"Hello, World!"}

代码实例

https://github.com/zhangcj/easymall/tree/master/springbootdemo/springbootdemo-shoppingcart
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息