使用IDEA建立SpringBoot多模块工程不爽啊~算了凑合用吧。
第一步、建立一个POM工程
..Next
..一路next即可,中间啥也不选
第二步、建立Eureka服务器(这个玩意等同于玩Dubbo时候的Zookeeper)
在项目上右键--
..还是Springboot
..
..选择依赖
..一路next即可
修改application.properties
server.port=8888 # 不向注册中心注册自己 eureka.client.register-with-eureka=false # 自己就是注册中心,职责是维护服务 eureka.client.fetch-registry=false # 服务端实例名称 eureka.instance.hostname=localhost #暴露的注册地址 eureka.client.service-url.defaultZone=http://localhost:8888/eureka
启动类添加注解
修改parent工程pom文件,也就是加一个module啦
<modules> <module>eureka-server</module> </modules>
修改本工程pom文件,把parent换成你建立的cloud-parent,而cloud-parent已经依赖了 spring-boot-starter-parent
<parent> <groupId>com.cloud</groupId> <artifactId>cloud-parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent>
接下来启动,先看一下注册中心的管控台http://localhost:8888/
什么都没有。等服务提供者出来就有了。
第三步、建立Common模块
..
..
..人家目录啥都没有,所以你得自己建
book类
package com.cloud.common.entity; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.Date; @Getter @Setter public class Book implements Serializable { private Long id; private String bookName; // 书名 private String bookSize; // 开本 private String pack; // 包装 private String ISBN; // isbn private String publisher; // 出版社 private Date publishTime; // 出版时间 }
BaseResponse
package com.cloud.common.response; import lombok.Getter; import lombok.Setter; import java.io.Serializable; @Getter @Setter public class BaseResponse<T> implements Serializable { private int code; private String desc; private T data; public BaseResponse(int code, String desc) { this.code = code; this.desc = desc; } }
加入依赖:
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
第四步、建立服务提供者
..
..
..完成后打开pom文件,注意这个东西,这个东西在前面版本是不一样的
..
加入额外的依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.6</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
在dependencies的最后加入common的依赖
<dependency> <groupId>com.cloud</groupId> <artifactId>cloud-common</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
把parent也改了
<parent> <groupId>com.cloud</groupId> <artifactId>cloud-parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent>
然后去父模块增加一个module
现在是代码部分:
配置文件:
server.port=8080 # 服务名 spring.application.name=BookServiceProvider spring.jackson.date-format=yyyy-MM-dd spring.jackson.time-zone=GMT+8 mybatis.config-location=classpath:mybatis/mybatis.xml mybatis.mapper-locations=classpath:mybatis/mapper/**/*.xml mybatis.type-aliases-package=com.cloud.common.entity spring.datasource.url=jdbc:mysql://localhost:3306/cloud?useSSL=false spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.username=root spring.datasource.password=1234 # 注册地址 eureka.client.service-url.defaultZone=http://localhost:8888/eureka # 注册名 eureka.instance.instance-id=book-service-provider eureka.instance.prefer-ip-address=true info.name: book-service-provider info.version: v1.0
启动类加上两个注解
@EnableEurekaClient
@EnableDiscoveryClient
DAO
package com.cloud.bookserviceprovider.dao; import com.cloud.common.entity.Book; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Mapper @Repository public interface BookDAO { int addBook(Book book); Book getBookById(@Param("id") Long id); List<Book> getBooks(); }
Service
package com.cloud.bookserviceprovider.service; import com.cloud.common.entity.Book; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BookService { int addBook(Book book); Book getBookById(@Param("id") Long id); List<Book> getBooks(); }
impl
package com.cloud.bookserviceprovider.service.impl; import com.cloud.bookserviceprovider.dao.BookDAO; import com.cloud.bookserviceprovider.service.BookService; import com.cloud.common.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BookServiceImpl implements BookService { @Autowired private BookDAO bookDAO; @Override public int addBook(Book book) { return bookDAO.addBook(book); } @Override public Book getBookById(Long id) { return bookDAO.getBookById(id); } @Override public List<Book> getBooks() { return bookDAO.getBooks(); } }
..BookDAOMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.cloud.bookserviceprovider.dao.BookDAO"> <insert id="addBook" parameterType="Book"> INSERT INTO book(bookName,bookSize,pack,isbn,publisher,publishTime) VALUES(#{bookName},#{bookSize},#{pack},#{ISBN},#{publisher},#{publishTime}) </insert> <select id="getBooks" resultType="Book"> select * from book </select> <select id="getBookById" resultType="Book"> select * from book where id=#{id} </select> </mapper>
mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 打印查询语句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> </configuration>
BookController
package com.cloud.bookserviceprovider.controller; import com.alibaba.fastjson.JSONObject; import com.cloud.bookserviceprovider.service.BookService; import com.cloud.common.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/book") public class BookController { @Autowired private BookService bookService; @Autowired private DiscoveryClient discoveryClient; @RequestMapping("/discovery") public Object discovery(){ List<String> services = discoveryClient.getServices(); services.forEach(e -> System.err.println(e)); List<ServiceInstance> list = discoveryClient.getInstances("BOOKSERVICEPROVIDER"); list.forEach(e -> { System.out.println(e.getServiceId() + "," + e.getHost() + "," + e.getPort() + "," + e.getUri()); }); return this.discoveryClient; } @RequestMapping("/add") public int addBook(@RequestBody Book book){ return bookService.addBook(book); } @RequestMapping("/get/{id}") public Book getBookById(@PathVariable("id") Long id){ return bookService.getBookById(id); } @RequestMapping("/getAll") public String getBooks(){ return JSONObject.toJSONString(bookService.getBooks()); } }
数据库脚本
CREATE TABLE `book` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `bookName` varchar(55) NOT NULL, `bookSize` varchar(10) NOT NULL, `pack` varchar(10) NOT NULL, `isbn` varchar(55) NOT NULL, `publisher` varchar(55) NOT NULL, `publishTime` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
整体目录:
现在呢,先启动注册中心,再启动服务提供者,打开管理界面,出现了一个服务
你点击,会出现
这就是application.properties配置的info信息。
第五步、建立服务消费者
..
..
修改pom文件(其实跟提供者类似)
把parent改成
<parent> <groupId>com.cloud</groupId> <artifactId>cloud-parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent>
加入common依赖
<dependency> <groupId>com.cloud</groupId> <artifactId>cloud-common</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
父工程pom,添加module
application.properties
server.port=8081
# 注册中心地址
eureka.client.service-url.defaultZone=http://localhost:8888/eureka
# 不向注册中心注册自己
eureka.client.register-with-eureka=false
配置类
package com.cloud.bookserviceconsumer.conf; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class ConsumerConfig { @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
controller
package com.cloud.bookserviceconsumer.controller; import com.cloud.common.entity.Book; import com.cloud.common.response.BaseResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("/consume/book") public class BookController { private static final String URL = "http://localhost:8080"; @Autowired private RestTemplate restTemplate; @RequestMapping("/add") public BaseResponse<Integer> addBook(@RequestBody Book book){ Integer integer = restTemplate.postForObject(URL + "/book/add", book, Integer.class); BaseResponse<Integer> response = new BaseResponse<>(0,"Success"); response.setData(integer); return response; } @RequestMapping("/get/{id}") public ResponseEntity<Book> getBookById(@PathVariable("id") Long id){ return restTemplate.getForEntity(URL + "/book/get/" + id,Book.class); } @RequestMapping("/getAll") public String getBooks(){ String s = restTemplate.getForObject(URL + "/book/getAll", String.class); return s; } }
最后访问
给你个示例json
{ "bookName": "Apache Kafka实战", "bookSize": "16开", "pack": "平装", "isbn": "9787121337765", "publisher": "电子工业出版社", "publishTime": "2018-05-01" }
添加操作
查询操作
最后展示一下服务发现(感觉很鸡肋),就是读取现有的服务名称