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

项目服务实例之间主要经过RestAPI方式进行通讯,因此服务自己可借助SpringBoot快速开发Restful web API。java

开发Restful web服务

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

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

使用工具:web

  • IDEA;
  • Mven3;

实体类

Hello.javaspring

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接口。api

HelloController.javatomcat

@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进行服务实例运行。springboot

@SpringBootApplication
public class Application {

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

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

maven打包,执行jar包:

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

访问http请求:

http://localhost:8080/greeting

响应结果:

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

代码实例

https://github.com/zhangcj/easymall/tree/master/springbootdemo/springbootdemo-shoppingcart

相关文章
相关标签/搜索