五、SpringCloud之商品服務
阿新 • • 發佈:2018-12-19
一、Eureka Server
pom.xml
<properties> <spring-cloud.version>Greenwich.M1</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies> <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> [Click and drag to move]
application.yml
#配置eureka
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
fetch-registry: false
server:
enable-self-preservation: false #關閉自我保護模式 開發環境關閉,生產環境不要這樣設定
spring:
application:
name: eureka
server:
port: 8761
Application
@EnableEurekaServer //啟用註冊中心的功能 @SpringBootApplication public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
二、商品服務
1、pom.xml
<properties> <spring-cloud.version>Greenwich.M1</spring-cloud.version> </properties> <dependencies> <!-- 引入eureka-client --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- 引入web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 引入data-jpa --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- 引入mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 引入lombok 可以省去get set方法 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <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>
2、application.yml
spring:
application:
name: product
datasource: #資料來源配置
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/SpringCloud_Sell?characterEncoding=utf-8&useSSL=false
jpa:
show-sql: true
eureka: #eureka配置
client:
service-url:
defaultZone: http://localhost:8761/eureka/
server: #埠號配置
port: 8888
3、Application
@EnableDiscoveryClient //開啟發現服務功能
@SpringBootApplication
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
}
4、Sql
-- 類目
create table `product_category` (
`category_id` int not null auto_increment,
`category_name` varchar(64) not null comment '類目名字',
`category_type` int not null comment '類目編號',
`create_time` timestamp not null default current_timestamp comment '建立時間',
`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改時間',
primary key (`category_id`),
unique key `uqe_category_type` (`category_type`)
);
INSERT INTO `product_category` (`category_id`, `category_name`, `category_type`, `create_time`, `update_time`)
VALUES
(1,'熱榜',11,'2017-03-28 16:40:22','2017-11-26 23:39:36'),
(2,'好吃的',22,'2017-03-14 17:38:46','2017-11-26 23:39:40');
-- 商品
create table `product_info` (
`product_id` varchar(32) not null,
`product_name` varchar(64) not null comment '商品名稱',
`product_price` decimal(8,2) not null comment '單價',
`product_stock` int not null comment '庫存',
`product_description` varchar(64) comment '描述',
`product_icon` varchar(512) comment '小圖',
`product_status` tinyint(3) DEFAULT '0' COMMENT '商品狀態,0正常1下架',
`category_type` int not null comment '類目編號',
`create_time` timestamp not null default current_timestamp comment '建立時間',
`update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改時間',
primary key (`product_id`)
);
INSERT INTO `product_info` (`product_id`, `product_name`, `product_price`, `product_stock`, `product_description`, `product_icon`, `product_status`, `category_type`, `create_time`, `update_time`)
VALUES
('157875196366160022','皮蛋粥',0.01,39,'好吃的皮蛋粥','//fuss10.elemecdn.com/0/49/65d10ef215d3c770ebb2b5ea962a7jpeg.jpeg',0,1,'2017-03-28 19:39:15','2017-07-02 11:45:44'),
('157875227953464068','慕斯蛋糕',10.90,200,'美味爽口','//fuss10.elemecdn.com/9/93/91994e8456818dfe7b0bd95f10a50jpeg.jpeg',1,1,'2017-03-28 19:35:54','2017-04-21 10:05:57'),
('164103465734242707','蜜汁雞翅',0.02,982,'好吃','//fuss10.elemecdn.com/7/4a/f307f56216b03f067155aec8b124ejpeg.jpeg',0,1,'2017-03-30 17:11:56','2017-06-24 19:20:54');
5、Entity
//商品
//@Table(name="product_info") //如果表名跟類名不一樣,要寫表名,一樣就不要
@Data //使用lombok省去get set方法
@Entity //資料庫與表對應
public class ProductInfo {
@Id //主鍵
private String productId;//id
private String productName;//名字
private BigDecimal productPrice;//單價
private Integer productStock;//庫存
private String productDescription;//描述
private String productIcon;//小圖
private Integer productStatus;//狀態, 0正常1下架
private Integer categoryType;//類目編號
private Date createTime;//建立時間
private Date updateTime;//修改時間
}
//類目
@Data
@Entity
public class ProductCategory {
@Id //主鍵
@GeneratedValue //id自增
private Integer categoryId;//類目id
private String categoryName;//類目名字
private Integer categoryType;//類目編號
private Date createTime;//建立時間
private Date updateTime;//修改時間
}
6、Dao
//商品
public interface ProductInfoRepository extends JpaRepository<ProductInfo,String> {
List<ProductInfo> findByProductStatus(Integer productStatus);
}
//類目
public interface ProductCategoryRepository extends JpaRepository<ProductCategory,Integer> {
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}
7、Service
//商品
public interface ProductService {
//查詢所有在架商品列表
List<ProductInfo> findUpAll();
}
//類目
public interface CategoryService {
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}
8、ServiceImpl
//商品
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductInfoRepository productInfoRepository;
@Override
public List<ProductInfo> findUpAll() {
return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
}
}
//類目
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired
private ProductCategoryRepository productCategoryRepository;
@Override
public List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList) {
return productCategoryRepository.findByCategoryTypeIn(categoryTypeList);
}
}
9、Enums
/**
* 商品上下線狀態
* */
@Getter //get方法
public enum ProductStatusEnum {
UP(0,"在架"),
DOWN(1,"下架"),
;
private Integer code;
private String message;
ProductStatusEnum(Integer code,String message){
this.code = code;
this.message = message;
}
}
10、Controller
/**
* 商品
* */
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@Autowired
private CategoryService categoryService;
@GetMapping("/list")
public ResultVO<ProductVO> list(){
//1.查詢所有在架的商品
List<ProductInfo> productInfoList = productService.findUpAll();
//2.獲取類目type列表
List<Integer> categoryTypeList = productInfoList.stream()
.map(ProductInfo::getCategoryType).collect(Collectors.toList());
//3.從資料庫查詢類目
List<ProductCategory> categoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
//4.構造資料
List<ProductVO> productVOList = new ArrayList<>();
for (ProductCategory productCategory:categoryList) {
ProductVO productVO = new ProductVO();
productVO.setCategoryName(productCategory.getCategoryName());
productVO.setCategoryType(productCategory.getCategoryType());
List<ProductInfoVO> productInfoVOList = new ArrayList<>();
for (ProductInfo productInfo:productInfoList) {
if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
ProductInfoVO productInfoVO = new ProductInfoVO();
BeanUtils.copyProperties(productInfo,productInfoVO);//將productInfo裡的屬性拷貝到productInfoVO裡面
productInfoVOList.add(productInfoVO);
}
}
productVO.setProductInfoVOList(productInfoVOList);
productVOList.add(productVO);
}
return ResultVOUtil.success(productVOList);
}
}
11、Utils
public class ResultVOUtil {
public static ResultVO success(Object object){
ResultVO resultVO = new ResultVO();
resultVO.setData(object);
resultVO.setCode(0);
resultVO.setMsg("成功");
return resultVO;
}
}
12、VO(返回頁面的Josn資料)
/**
*http請求返回的最外層物件
* */
@Data
public class ResultVO<T> {
private Integer code;//錯誤碼
private String msg;//提示資訊
private T data;//具體內容
}
@Data
public class ProductVO {
@JsonProperty("name") //返回前端顯示的欄位
private String categoryName;//內目名字
@JsonProperty("type")
private Integer categoryType;//類目編號
@JsonProperty("foods")
private List<ProductInfoVO> productInfoVOList;//食物
}
@Data
public class ProductInfoVO {
@JsonProperty("id")
private String productId;
@JsonProperty("name")
private String productName;
@JsonProperty("price")
private String productPrice;
@JsonProperty("description")
private String productDescription;
@JsonProperty("icon")
private String productIcon;
}
13、Test
測試結果: