SpringCloud(第 004 篇)用户服务类(添加服务注册,将用户微服务注册到 EurekaServer 中)
-
一、大致介绍
通过添加注解 EnableEurekaClient,将用户微服务注册到 EurekaServer 中。
二、实现步骤
2.1 添加 maven 引用包
<?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>
<artifactId>springms-provider-user</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.springms.cloud</groupId>
<artifactId>springms-spring-cloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- 访问数据库模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- web模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- h2数据库模块 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 客户端发现模块 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!-- 监控和管理生产环境的模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
2.2 添加应用配置文件(springms-provider-usersrcmainresourcesapplication.yml)
server:
port: 7900
spring:
jpa:
generate-ddl: false
show-sql: true
hibernate:
ddl-auto: none
datasource:
platform: h2
schema: classpath:schema.sql
data: classpath:data.sql
application:
name: springms-provider-user #全部小写
logging:
level:
root: INFO
org.hibernate: INFO
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org.bibernate.type.descriptor.sql.BasicExtractor: TRACE
com.springms: DEBUG
eureka:
client:
service-url:
# defaultZone: http://localhost:8761/eureka/ #不需要认证
defaultZone: http://admin:admin@localhost:8761/eureka #需要认证
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
# 元数据测试
metadata-map:
zone: ABC # eureka 可以理解的元数据
hmily: HMILYYLIMH # 不会影响客户端行为
# appname: appname-springms-provider-user # 直接显示的是App应用的名称,在 http://localhost:8761/ 地址处可以看到该注册服务的应用名称
# # 这里我们就先注释掉,知道这个 hostname 的用法就可以了,先注释掉不影响后面的测试
# hostname: user # 然后我们就可以通过 http://user:7900/simple/1 来访问我们的地址了
2.3 添加 H2 数据库脚本(springms-provider-usersrcmainresourcesschema.sql)
drop table user if exists;
CREATE TABLE USER(
id BIGINT GENERATED by default as identity,
username VARCHAR(40),
name VARCHAR(20),
age int(3),
balance DECIMAL(10, 2),
PRIMARY KEY(id)
);
2.4 插入 H2 数据库一些初始化数据(springms-provider-usersrcmainresourcesdata.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', '李四', 22, 100.00);
INSERT into user (id, username, name, age, balance) values (3, 'user3', '王五', 24, 100.00);
INSERT into user (id, username, name, age, balance) values (4, 'user4', '赵六', 26, 100.00);
INSERT into user (id, username, name, age, balance) values (5, 'user5', '李逵', 27, 100.00);
INSERT into user (id, username, name, age, balance) values (6, 'user6', '张远', 10, 100.00);
INSERT into user (id, username, name, age, balance) values (7, 'user7', '迪拜', 60, 100.00);
INSERT into user (id, username, name, age, balance) values (8, 'user8', '哈士奇', 40, 100.00);
INSERT into user (id, username, name, age, balance) values (9, 'user9', '关羽', 30, 100.00);
2.5 添加访问底层数据模型的DAO接口(springms-provider-usersrcmainjavacomspringmscloudrepositoryUserRepository.java)
package com.springms.cloud.repository;
import com.springms.cloud.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
2.6 添加实体用户类User(springms-provider-usersrcmainjavacomspringmscloudentityUser.java)
package com.springms.cloud.entity;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@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 this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Short getAge() {
return this.age;
}
public void setAge(Short age) {
this.age = age;
}
public BigDecimal getBalance() {
return this.balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
2.7 添加用户Web访问层Controller(springms-provider-usersrcmainjavacomspringmscloudcontrollerUserController.java)
package com.springms.cloud.controller;
import com.google.common.collect.Lists;
import com.springms.cloud.entity.User;
import com.springms.cloud.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* 用户界面控制层。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017/9/17
*
*/
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
// @Autowired
// private EurekaClient discoveryClient;
@GetMapping("/simple/{id}")
public User findById(@PathVariable Long id){
return userRepository.findOne(id);
}
// public String serviceUrl(){
// InstanceInfo instance = this.discoveryClient.getNextServerFromEureka("SPRINGMS-PROVIDER-USER", false);
// return instance.getHomePageUrl();
// }
@PostMapping("/user")
public User postUser(@RequestBody User user){
System.out.println("@GetMapping(\"user\") 接收参数对象 user: " + user);
return user;
}
@GetMapping("listAll")
public List<User> listAll(){
ArrayList<User> list = Lists.newArrayList();
User user1 = new User(1L, "user1");
User user2 = new User(1L, "user2");
User user3 = new User(1L, "user3");
User user4 = new User(1L, "user4");
User user5 = new User(1L, "user5");
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
list.add(user5);
return list;
}
}
2.8 添加用户微服务启动类(springms-provider-usersrcmainjavacomspringmscloudMsProviderUserApplication.java)
package com.springms.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* 用户服务类(添加服务注册,将用户微服务注册到 EurekaServer 中)。
*
* @author hmilyylimh
*
* @version 0.0.1
*
* @date 2017/9/17
*
*/
@SpringBootApplication
@EnableEurekaClient
public class MsProviderUserApplication {
public static void main(String[] args) {
SpringApplication.run(MsProviderUserApplication.class);
System.out.println("【【【【【【 用户微服务 】】】】】】已启动.");
}
}
三、测试
/****************************************************************************************
一、用户微服务接口测试:
1、注解:EnableEurekaClient
2、启动 springms-discovery-eureka 模块服务,启动1个端口;
3、启动 springms-provider-user 模块服务,启动1个端口;
4、在浏览器输入地址http://localhost:7900/simple/1 可以看到信息成功的被打印出来,说明用户微服务正常;
5、在浏览器输入地址 http://localhost:8761 并输入用户名密码 admin/admin 进入Eureka微服务显示在网页中,说明用户微服务确实注册到了 eureka 服务中;
6、在浏览器输入地址 http://localhost:8761/eureka/apps/springms-provider-user 可以看到自定义的 <metadata>信息以及用户微服务的相关信息成功的被展示出来了;
****************************************************************************************/
/****************************************************************************************
二、用户微服务接口测试(给 springms-discovery-eureka-ha 模块做测试,测试EurekaClient客户端注册进EurekaServer高可用集群中):
1、注解:EnableEurekaClient
2、修改 defaultZone 的接入地址值如下:
###################################################################################
# 测试二:测试EurekaClient客户端注册进EurekaServer高可用集群中
defaultZone: http://admin:admin@peer1:8401/eureka,,http://admin:admin@peer2:8402/eureka,,http://admin:admin@peer3:8403/eureka
###################################################################################
3、启动 springms-discovery-eureka-ha 模块服务,启动3个端口;
4、启动 springms-provider-user 模块服务,启动1个端口;
5、在浏览器输入地址http://localhost:7900/simple/1 可以看到信息成功的被打印出来,说明用户微服务正常;
6、在浏览器输入地址 http://localhost:8401 并输入用户名密码 admin/admin 进入Eureka微服务显示在网页中,说明用户微服务确实注册到了 eureka 服务中;
7、在浏览器输入地址 http://localhost:8401/eureka/apps/springms-provider-user 可以看到自定义的 <metadata>信息以及用户微服务的相关信息成功的被展示出来了;
8、在浏览器输入地址 http://localhost:8402/eureka/apps/springms-provider-user 可以看到自定义的 <metadata>信息以及用户微服务的相关信息成功的被展示出来了;
9、在浏览器输入地址 http://localhost:8403/eureka/apps/springms-provider-user 可以看到自定义的 <metadata>信息以及用户微服务的相关信息成功的被展示出来了;
****************************************************************************************/
四、下载地址
https://gitee.com/ylimhhmily/SpringCloudTutorial.git
SpringCloudTutorial交流QQ群: 235322432
SpringCloudTutorial交流微信群: 微信沟通群二维码图片链接
欢迎关注,您的肯定是对我最大的支持!!!