Spring-Cloud 学习笔记-(2)项目搭建
Spring-Cloud 学习笔记-(2)项目搭建
1、环境介绍
2、主项目搭建
2.1.新建一个Maven项目作为主项目
2.2.填写项目信息
2.3.pom文件引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bigfly</groupId>
<artifactId>cloud-demo</artifactId>
<version>1.0.0-SNAPSHOT</version>
<!--设置打包方式-->
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<!--版本号统一管理-->
<properties>
<java.verion>1.8</java.verion>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>
<!--spring-cloud 版本,后面子项目直接拿坐标-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
2.4.导入依赖
2.4.1.idea配置maven
2.4.2.修改maven仓库为阿里仓库
修改maven下面的/conf/setting.xml文件
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
2.4.3.拉取依赖
3、服务提供者
在主项目下创建一个moduel作为服务提供者,对外提供用户信息查询服务
3.1.新建一个Module
为了便于管理我们把没用的文件夹:
主项目中的src
新建Module:
依旧新建一个Maven项目:
填写项目信息:
目录结构:
3.2.修改pom文件
增加spring-boot-starter-web 依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud-demo</artifactId>
<groupId>com.bigfly</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>user-service</artifactId>
<dependencies>
<!-- spring-boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
拉取依赖:
创建必要文件:
3.2.创建spring-boot启动类
@SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class);
}
}
3.3.创建测试类
@RestController
@RequestMapping("api/v1/user")
public class UserController {
@RequestMapping("/test")
public String test(){
return "我是用户服务,我是服务的提供者";
}
}
3.4.测试效果
访问:http://localhost:8080/api/v1/user/test
3.5.编写模拟获取用户信息代码
数据包装类:
package com.bigfly.common;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/*
* @Author 程鹏飞
* @Description //TODO 数据包装类
* @Date 01:58 2018/12/9 0009
**/
@Component
public class BaseData {
/**
* 返回状态码:1:成功 0:失败
*/
private int code;
/**
* 返回数据
*/
private Object data;
/**
* 错误消息
*/
private String errorMsg;
/**
* 空参构造器
*/
public BaseData() {
}
/**
* 返回成功构造器
*/
public BaseData(Object data) {
this.code = 1;
this.data = data;
}
/**
* 返回失败构造器
*/
public BaseData(String errorMsg,Object data) {
this.code = 0;
this.errorMsg = errorMsg;
this.data = data;
}
/**
* getter setter方法
*/
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
User对象:
package com.bigfly.entity;
/*
* @Author 程鹏飞
* @Description //TODO 用户对象
* @Date 02:06 2018/12/9 0009
**/
public class User {
/**
* 用户id
*/
private int id;
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private int age;
/**
* 端口号 表示从哪个端口过来的User
*/
private String port;
/**
* 空参构造器
*/
public User() {
}
/**
*id,name,age构造器
*/
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
/**
* getter setter方法
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
UserService接口:
package com.bigfly.service.service;
import com.bigfly.entity.User;
public interface UserService {
/**
* 根据id查询用户基本信息
* @param id 用户id
* @return 用户对象
*/
User findById(int id);
}
UserServiceImpl实现类:
package com.bigfly.service.service.impl;
import com.bigfly.entity.User;
import com.bigfly.service.service.UserService;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService {
/**
* 模拟数据库
*/
private static Map<Integer,User> userMap = new HashMap<>();
static {
User u1 = new User(1,"张三",11);
User u2 = new User(2,"李四",12);
User u3 = new User(3,"王五",13);
userMap.put(u1.getId(),u1);
userMap.put(u2.getId(),u2);
userMap.put(u3.getId(),u3);
}
/**
* 根据id查询用户基本信息
* @param id 用户id
* @return 用户对象
*/
@Override
public User findById(int id) {
return userMap.get(id);
}
}
UserController里面增加:
@Autowired
private UserService userService;
@RequestMapping("{user_id}")
public BaseData findUserById(@PathVariable("user_id")int id){
User user = userService.findById(id);
return new BaseData(user);
}
测试:
访问:http://localhost:8080/api/v1/user/2
4、服务消费者
4.1.根据上面方法创建一个消费者Module
目录结构:
pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud-demo</artifactId>
<groupId>com.bigfly</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>order-service</artifactId>
<dependencies>
<!-- spring-boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
4.2.编写代码
数据包装类:
package com.bigfly.common;
/*
* @Author 程鹏飞
* @Description //TODO 数据包装类
* @Date 01:58 2018/12/9 0009
**/
public class BaseData {
/**
* 返回状态码:1:成功 0:失败
*/
private int code;
/**
* 返回数据
*/
private Object data;
/**
* 错误消息
*/
private String errorMsg;
/**
* 空参构造器
*/
public BaseData() {
}
/**
* 返回成功构造器
*/
public BaseData(Object data) {
this.code = 1;
this.data = data;
}
/**
* 返回失败构造器
*/
public BaseData(int code, String errorMsg) {
this.code = 0;
this.errorMsg = errorMsg;
}
/**
* getter setter方法
*/
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
Order订单实体类:
package com.bigfly.entity;
/*
* @Author 程鹏飞
* @Description //TODO 订单实体类
* @Date 03:43 2018/12/9 0009
**/
public class Order {
/**
* 订单名称
*/
private String orderName;
/**
* 订单流水号
*/
private String serialId;
/**
* 用户名称
*/
private String userName;
/**
* 端口号
*/
private String port;
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public String getSerialId() {
return serialId;
}
public void setSerialId(String serialId) {
this.serialId = serialId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
OrderService订单接口:
package com.bigfly.service;
import com.bigfly.entity.Order;
/*
* @Author 程鹏飞
* @Description //TODO 订单接口
* @Date 03:32 2018/12/9 0009
**/
public interface OrderService {
/**
* 根据用户id 查询用户信息
* @param userId 用户id
* @return
*/
Order findById(int userId);
}
OrderServiceImpl 接口实现类:
package com.bigfly.service.impl;
import com.bigfly.entity.Order;
import com.bigfly.service.OrderService;
import org.springframework.stereotype.Service;
@Service
public class OrderServcieImpl implements OrderService {
/**
* 根据用户id 查询用户信息
* @param userId 用户id
* @return
*/
@Override
public Order findById(int userId) {
return null;
}
}
OrderController:
package com.bigfly.controller;
import com.bigfly.common.BaseData;
import com.bigfly.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("api/v1/order")
public class OrderController {
@RequestMapping("test")
public String test(){
return "我是订单服务,我是服务的消费者";
}
@Autowired
private OrderService orderService;
@RequestMapping("{user_id}")
public BaseData findUserById(@PathVariable("user_id")int id){
Order order = orderService.findById(id);
return new BaseData(order);
}
}
OrderApplication启动类:
package com.bigfly;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class);
}
}
4.3.测试
访问:http://localhost:8080/api/v1/order/test
5、RestTemplate的使用
5.1.修改代码
5.1.1.代码修改(user-service)####
UserServiceImpl:
package com.bigfly.service.service.impl;
import com.bigfly.entity.User;
import com.bigfly.service.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService {
/**
* 获取application.yml配置文件中的端口号
*/
@Value("${server.port}")
private String port;
/**
* 模拟数据库
*/
private static Map<Integer,User> userMap = new HashMap<>();
static {
User u1 = new User(1,"张三",11);
User u2 = new User(2,"李四",12);
User u3 = new User(3,"王五",13);
userMap.put(u1.getId(),u1);
userMap.put(u2.getId(),u2);
userMap.put(u3.getId(),u3);
}
/**
* 根据id查询用户基本信息
* @param id 用户id
* @return 用户对象
*/
@Override
public User findById(int id) {
User user = userMap.get(id);
//把端口号放入User对象
user.setPort(port);
return user;
}
}
application.yml增加:
#修改默认端口
server:
port: 8771
5.1.2.代码修改(order-service)####
添加Json工具类
添加utils包,在utils包下面创建JsonUtils
package com.bigfly.utils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
/*
* @Author 程鹏飞
* @Description //TODO Json 工具类
* @Date 03:57 2018/12/9 0009
* @return
**/
public class JsonUtils {
private static ObjectMapper mapper = new ObjectMapper();
/**
* 字符串 转 JsonNode
* @param str
* @return
*/
public static JsonNode str2JsonNode(String str) {
if (StringUtils.isBlank(str)) {
return null;
}
JsonNode jsonNode = null;
try {
jsonNode = mapper.readTree(str);
} catch (Exception e) {
e.printStackTrace();
}
return jsonNode;
}
}
application.yml增加:
#修改默认端口
server:
port: 8781
OrderApplication增加:
/**
* 把RestTemplate注入到Spring容器中
*/
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
OrderServiceImpl:
package com.bigfly.service.impl;
import com.bigfly.entity.Order;
import com.bigfly.service.OrderService;
import com.bigfly.utils.JsonUtils;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.UUID;
@Service
public class OrderServcieImpl implements OrderService {
@Autowired
private RestTemplate restTemplate;
/**
* 根据用户id 查询用户信息
* @param userId 用户id
* @return
*/
@Override
public Order findById(int userId) {
//getForObject 第一个参数url代表访问路径 第二个参数代表 返回值类型
String jsonStr = restTemplate.getForObject("http://localhost:8771/api/v1/user/2", String.class);
JsonNode jsonNode = JsonUtils.str2JsonNode(jsonStr);
Order order = new Order();
order.setOrderName("我是一个订单");
order.setSerialId(UUID.randomUUID().toString());
order.setUserName(jsonNode.get("data").get("name").textValue());
order.setPort(jsonNode.get("data").get("port").textValue());
return order;
}
}