项目地址:
http://gitlab.zack.net.cn/root/springcloudexample
##########################################################
创建Microservice_Example1模块
-
在SpringCloudExample项目下创建一个模块, 用于注册到eureka server
-
编辑Microservice_Example1模块的pom文件
引入web依赖和eureka client依赖
<packaging>jar</packaging>
<dependencies>
<!--引入web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--注册到eureka server注册中心只需要eureka客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--引入lombok依赖, 用于简化实体类的get,set,构造函数等等-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
-
编辑Microservice_Example1模块的配置文件
server:
port: 8001
# 应用名(微服务名)
spring:
application:
name: microservice-example
eureka:
instance:
# 是否注册到eureka server
prefer-ip-address: true
# 当前实例主机名
hostname: microservice_example1
client:
service-url:
# eureka server1注册中心的地址
defaultZone: http://localhost:8761/eureka
-
编辑Microservice_Example1的启动类
package cn.zack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author zack
* 只对外提供服务的服务提供者一
*/
@SpringBootApplication
public class Microservice_Example1_Application {
public static void main(String[] args) {
SpringApplication.run(Microservice_Example1_Application.class, args);
}
}
-
在Microservice_Example1模块创建一个User类
package cn.zack.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author zack
* User实体类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String username;
private String password;
}
-
在Microservice_Example1模块编写方法供外部调用
package cn.zack.controller;
import cn.zack.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
/**
* @author zack
* 服务提供者一
*/
@Slf4j
@RestController
public class ExampleController {
@GetMapping(path = "fun1")
public String fun1() throws InterruptedException {
log.info("test入参======");
// Thread.sleep(100000);
return "调用example1.fun1";
}
@GetMapping(path = "fun2")
public String fun2(String param1, String param2) {
log.info("test入参======, param1:{}, param2:{}", param1, param2);
return "param1 : " + param1 + "\r\nparam2 : " + param2;
}
@PostMapping(path = "/fun4")
public String fun4(@RequestBody User user) {
// 手动添加除零异常
int a = 1 / 0;
return "username: " + user.getUsername() + "\r\npassword: " + user.getPassword();
}
}
-
先启动Example_Eureka1, 再启动Microservice_Example1
可以看到eureka注册中心启动正常, eureka server本身和Microservice_Example1都成功注册为服务.
而Microservice_Example1提供的服务也可以正常使用.