SpringCloud實戰微服務

版本:CamdenSR1java

SpringCloud特色:約定優於配置、開箱即用,快速啓動、適用於各類環境、輕量級組件、組件的支持很豐富,功能齊全(配置中心,註冊中心,智能路由)、選型中立(EuraKa、Zookeeper、consul)。mysql

把maven項目轉換成gradle項目  在文件夾立打開命令行窗口,輸入: fradle init --type pom 便可web

會生成一個build.gradle文件.spring

服務提供者於服務消費者:sql

        服務提供者:服務的被調用方(即,爲其餘服務提供服務的服務);springboot

        服務消費者:服務的調用方(即,依賴其餘服務的服務);app

好比電影院購票系統:用戶就是服務提供者,提供一個購票的消費接口,maven

                                  購票的微服務,就是服務消費者,調用用戶提供的接口,完成消費;ide

接下來,讓咱們來寫一個小demo:微服務

            進入這個網址:https://start.spring.io

顯示以下界面

選擇maven和springboot的版本號 

建立咱們的項目及咱們所須要的組件

須要組件 web、jpa、mysql

而後點擊下面的綠色按鈕,下載

以後解壓

使用開發工具 IDEA,導入maven項目

選擇咱們要導入項目的pom文件,點擊ok

在咱們的resource目錄下,編寫咱們的建表語句和一些測試數據

schema.sql  :建表語句

drop table if EXISTS user;
CREATE  TABLE user (
   id int NOT NULL AUTO_INCREMENT ,
    username VARCHAR (20),
    name VARCHAR (20),
    age int (5),
    balance DECIMAL (20,2),
    PRIMARY  KEY (id)
);

data.sql:測試數據

insert into user (id,username,name,age,balance) VALUES (1,'user1','張三',20,'100.00');
insert into user (id,username,name,age,balance) VALUES (2,'user2','李四',20,'100.00');
insert into user (id,username,name,age,balance) VALUES (3,'user3','王五',20,'100.00');
insert into user (id,username,name,age,balance) VALUES (4,'user4','趙六',20,'100.00');
insert into user (id,username,name,age,balance) VALUES (5,'user5','王麻子',20,'100.00');

建立包結構

因爲SimpleProviderUserApplication 是啓動類,必須放在最外層

配置咱們的配置文件改名爲:application.yml

server:
  port: 7900    #配置端口號
spring:
  jpa:
    generate-ddl: false    #啓動的時候要不要生成ddl語句
    show-sql: true #爲了打印sql語句
 #由於jpa依賴hibernate, 這個也是ddl語句的配置,設置爲none
    hibernate:
      ddl-auto: none
 #配置數據源
        # MySQL database
  datasource:
    platform: mysql
    url: jdbc:mysql://localhost:3306/macroservice?useUnicode=true&characterEncoding=utf-8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    schema: classpath:schema.sql
    data: classpath:data.sql

 #顯示sql語句,並把參數什麼的打印出來
logging:
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
    com.itmuch: DEBUG

在entity包下,編寫咱們的實體類,並生產setget

package com.example.simpleprovideruser.entity;

import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;

/**
 * Created by dell on 2017/9/5.
 */
@Entity
public class User implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column
    private String username;
    @Column
    private String name;
    @Column
    private short age;
    @Column
    private BigDecimal balance;

    public Long getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getName() {
        return name;
    }

    public short getAge() {
        return age;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(short age) {
        this.age = age;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }
}

在dao包下,編寫咱們的接口,並繼承 JpaRepository

package com.example.simpleprovideruser.dao;

import com.example.simpleprovideruser.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Created by dell on 2017/9/5.
 */
public interface UserDao extends JpaRepository<User,Long> {


}

接着編寫咱們的controller

package com.example.simpleprovideruser.Controller;

import com.example.simpleprovideruser.dao.UserDao;
import com.example.simpleprovideruser.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by dell on 2017/9/5.
 */

@RestController
public class UserController {
    @Autowired
    private UserDao userDao;
    @GetMapping("/user/{id}")
    public User findById(@PathVariable Long id){
        return userDao.findOne(id);
    }
}

啓動項目效果以下:

沒有報錯,輸入

及完成了服務提供者的搭建!

接下來是消費者的搭建:

導入建立好的消費者項目

包結構以下:

        編寫User實體類

package com.example.simpleconsumermovie.entity;

import java.math.BigDecimal;

/**
 * Created by dell on 2017/9/5.
 */
public class User {

    private Long id;
    private String username;
    private String name;
    private short age;
    private BigDecimal balance;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public short getAge() {
        return age;
    }

    public void setAge(short age) {
        this.age = age;
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }
}

編寫controller

package com.example.simpleconsumermovie.controller;

import com.example.simpleconsumermovie.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by dell on 2017/9/5.
 */
@RestController
public class MovieController {

    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/movie/{id}")
    public User findById(@PathVariable Long id){
        return this.restTemplate.getForObject("http://localhost:7900/user/" + id , User.class);
    }
}

在調用的方法中實例化提供的RestTemplate方法

package com.example.simpleconsumermovie;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class SimpleConsumerMovieApplication {
   @Bean
   public RestTemplate restTemplate(){
      return  new RestTemplate();
   }

   public static void main(String[] args) {

      SpringApplication.run(SimpleConsumerMovieApplication.class, args);
   }
}

配置yml文件的端口號

server:
  port: 7901  #配置端口號

接下來,首先啓動服務提供者,在啓動消費者‘

頁面輸入

這樣就實現了,消費者調用服務者的這樣一個服務。

相關文章
相關標籤/搜索