1. 程式人生 > >SpringCloud零基礎上手(三)——服務註冊

SpringCloud零基礎上手(三)——服務註冊

上一篇我們建了一個多模組專案結構,用於編寫login服務,我們接著上篇的內容 ,閒話少說,直接上碼。

一、login服務提供介面的模組pf-login-client

1、啟動類LoginClientApplication

package cn.pw.platform;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix
.eureka.EnableEurekaClient; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @EnableEurekaClient public class LoginClientApplication { public static void main(String[] args) { SpringApplication.run(LoginClientApplication.class,args); } }

新增@EnableEurekaClient 註解,使得login服務成為Eureka的一個客戶端,通過載入配置檔案將服務註冊到Eureka Server 註冊中心。

2、配置檔案application.yml

server:
  port: 8010

eureka:
  client:
    service-url:
      default-zone: http://127.0.0.1:8761/eureka/
    instance:
      instance-id: ${spring.cloud.client.ipAddress}
      prefer-ip-address: true

spring:
  application:
    name: pf-login-server
  jpa:
    database: mysql
    show-sql
: true hibernate: ddl-auto: update naming: strategy: org.hibernate.cfg.ImprovedNamingStrategy datasource: url: jdbc:mysql://localhost:3306/pw_base_db username: root password: root driver-class-name: com.mysql.jdbc.Driver

這各配置檔案包三部分內容,最上面是指定了服務執行埠號8010,中間部分向註冊中心地址,多個地址中間用逗號隔開達到高可用,最後一部分是資料來源,主要是Dao層使用。

3、服務暴露的介面*(基於RESTful風格的api)*

package cn.pw.platform.login.client;

import cn.pw.platform.dao.po.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

public interface LoginClient {
    @GetMapping("/selectUserByName/{userName}")
    User selectUserByName(@PathVariable("userName") String userName);

    @PostMapping("/user/add")
    User addUser(@RequestBody User user);
}

4、介面實現類

package cn.pw.platform.login.client.impl;

import cn.pw.platform.dao.po.User;
import cn.pw.platform.login.client.LoginClient;
import cn.pw.platform.login.server.service.LoginServer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginClientImpl implements LoginClient {
    @Autowired
    private LoginServer loginServer;

    @Override
    public User selectUserByName(@PathVariable("userName") String userName) {
        return loginServer.findByName(userName);
    }

    @Override
    public User addUser(@RequestBody User user) {
        return loginServer.addUser(user);
    }
}

非常常見和常規的RESTful風格寫法,沒有什麼可說的,這樣服務提供介面就定義好了,下面在server模組中實現業務邏輯。

二、login服務業務的邏輯模組pf-login-server

1、啟動類LoginServerApplication

package cn.pw.platform;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;


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

由於server模組最終是依jar的形式被client依賴,我習慣上所有配置都寫在client中,方便統一維護。

2、邏輯介面

package cn.pw.platform.login.server.service;

import cn.pw.platform.dao.po.User;

public interface LoginServer {

    User addUser(User user);
    User findByName(String userName);
}

3、邏輯實現

package cn.pw.platform.login.server.serviceImpl;

import cn.pw.platform.dao.UserRepository;
import cn.pw.platform.dao.po.User;
import cn.pw.platform.login.server.service.LoginServer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class LoginServerImpl implements LoginServer{

    @Autowired
    private UserRepository userRepository;

    @Override
    public User addUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public User findByName(String userName) {
        return userRepository.findUserByName(userName);
    }

}

三、login服務業務的持久模組pf-login-dao

1、啟動類DaoApplication

package cn.pw.platform;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

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

2、進行持久 操作,自定義Repository介面,實現JpaRepository,剩下的交給SpringBoot

package cn.pw.platform.dao;

import cn.pw.platform.dao.po.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import org.springframework.stereotype.Repository;

import javax.persistence.Table;

@Repository
@Table(name="user")
public interface UserRepository extends JpaRepository<User, Long> {

    User findById(Long id);

    User save(User user);

    @Query("select t from User t where t.name=:name")
    User findUserByName(@Param("name") String name);
}

3、實體類User

package cn.pw.platform.dao.po;

import javax.persistence.*;

@Entity
@Table(name="user")
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    private String name;

    @Column(name = "nick_name")
    private String nickName;

    private String password;

    private Integer age;

    private Integer sex;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public Integer getAge() {
        return age;
    }

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

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }


    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

四、測試
1、啟動Eureka Server 註冊中心。
2、啟動login服務,通過client模組的LoginClientApplication類啟動。
3、開啟註冊中心 http://localhost:8761/ ,這會能看到我們的服務已經註冊了。
這裡寫圖片描述

4、通過postman 工具呼叫我們寫的兩個介面

這裡寫圖片描述

細節:@RequestBody接收的引數 ,傳參時必須是json格式。如果不行搞這麼搞,就用 @RequestParam 逐個接收,然後再自己編碼注入到實體中 。

這裡寫圖片描述

這只是個demo,功能 既簡單,使用如此繁瑣的多模組可能初學者會很嫌棄,但是實際專案中,這樣做大有好處。