Spring Cloud Eureka是什么?
Spring Cloud Eureka是Spring Cloud Netflix微服务套件中的一部分,它基于Netflix
Eureka做了二次封装,主要负责完成微服务架构中的服务治理功能。Spring Cloud通过为Eureka增加了Spring
Boot风格的自动化配置,我们只需通过简单引入依赖和注解配置就能让Spring
Boot构建的微服务应用轻松地与Eureka服务治理体系进行整合。
关于Eureka的更多理论,可以参考《Spring Cloud微服务实战》第3章内容。
本项目是一个多模块项目,每个独立功能被抽取为一个Module,这样便于在IntelliJ IDEA中管理项目,避免了在不同的Project窗口来回切换。
新建一个Module,命名为mall-crud,引入Lombok依赖。
其中的实体类来自我的博文《SpringBoot+MySQL+MyBatis(Mapper.xml方式)实现简单的多表CRUD(RESTful风格HTTP接口)》
User.java
package com.jake.mallmodel.entity;
import lombok.Data;
@Data
public class User {
private Integer uid;
private String username;
private String password;
}
UserInfo.java
package com.jake.mallmodel.entity;
import lombok.Data;
import java.util.List;
@Data
public class UserInfo {
private List users;
private String cname;
private String city;
}
此模块是Eureka的服务之一,对外提供User和UserInfo的增删改查操作,其CRUD三层架构代码也来自我的博文《SpringBoot+MySQL+MyBatis(Mapper.xml方式)实现简单的多表CRUD(RESTful风格HTTP接口)》,可以在IntelliJ IDEA中直接引入已存在的模块:
修改项目名为mall-crud(同时也修改包名),删除实体类,并在pom文件中(1)引入Eureka Server相关的依赖,(2)引入mall-model项目依赖,以便于导入User和UserInfo实体类:
pom.xml
4.0.0
com.jake
mall-crud
0.0.1-SNAPSHOT
jar
mall-crud
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.1.3.RELEASE
UTF-8
UTF-8
1.8
Greenwich.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.0
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
true
com.alibaba
fastjson
1.2.54
com.jake
mall-model
0.0.1-SNAPSHOT
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/eureka-db?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username: root
password: 123
driver-class-name: com.mysql.cj.jdbc.Driver
application:
name: mall-crud
mybatis:
mapper-locations: classpath:mapper/*xml
server:
port: 8083
eureka:
client:
service-url:
defaultZone: http://localhost:8081/eureka/
在启动类上加入@EnableEurekaClient注解,标志这是Eureka客户端,可以将自身注册到服务端上。
package com.jake.eurekaclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}
为了方便与后面Eureka客户端调用接口的代码比较,在此处贴出CRUD接口所在控制层的代码:
package com.jake.mallcrud.controller;
import com.jake.mallcrud.service.UserService;
import com.jake.mallmodel.entity.User;
import com.jake.mallmodel.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("users")
public class UserController {
@Autowired
private UserService userService;
/**
* 查找所有用户
* @return
*/
@GetMapping
public List findAllUsers() {
return userService.findAllUsers();
}
/**
* 查找所有用户信息
* @return
*/
@GetMapping("info")
public List findAllUserInfo() {
return userService.findAllUserInfo();
}
/**
* 通过id查找用户
* @param uid
* @return
*/
@GetMapping("{uid}")
public User findUserById(@PathVariable Integer uid) {
return userService.findUserById(uid);
}
/**
* 通过id查找用户信息
* @param uid
* @return
*/
@GetMapping("info/{uid}")
public UserInfo findUserInfoById(@PathVariable Integer uid) {
return userService.findUserInfoById(uid);
}
/**
* 通过用户名和公司名查找用户
* @param username
* @param cname
* @return
*/
@GetMapping("info/{cname}/{username}")
public List findUserInfoByUsernameAndCname(@PathVariable String username, @PathVariable String cname) {
return userService.findUserInfoByUsernameAndCname(username, cname);
}
/**
* 新增用户
* @param user
* @return
*/
@PostMapping
public String createUser(@RequestBody User user) {
if (user != null) {
userService.createUser(user);
return "添加用户成功";
} else {
return "添加用户失败";
}
}
/**
* 修改用户
* @param user
* @return
*/
@PutMapping
public String updateUser(@RequestBody User user) {
User userInDb = userService.findUserById(user.getUid());
if (userInDb != null) {
userService.updateUser(user);
return "更新用户成功";
} else {
return "更新用户失败";
}
}
/**
* 删除用户
* @param uid
* @return
*/
@DeleteMapping("{uid}")
public String removeUserById(@PathVariable Integer uid) {
User user = userService.findUserById(uid);
if (user == null) {
return "数据库中不存在id为" + uid + "的用户";
} else {
userService.removeUserById(uid);
return "删除成功";
}
}
}
Eureka服务端是一个服务注册和发现中心,并可以通过心跳检测时刻更新微服务的注册信息。
新建一个Module,命名为eureka-server,在Dependencies中选择Cloud Discovery,建立好工程:
在启动类上加入@EnableEurekaServer注解,标记这是Eureka服务端:
package com.jake.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
application.yml中做如下配置:
server:
port: 8081
eureka:
instance:
hostname: eureka-server
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
其中配置文件中各个变量的作用可通过查看源码的注释了解。
新建模块,选择的Dependencies如下图:
此模块用于测试,可以调用其他注册到Eureka Server的服务提供的接口,同时其自身也是一个服务。本文中用于调用mall-crud提供的CRUD接口。
application.yml:
eureka:
client:
service-url:
defaultZone: http://localhost:8081/eureka/
server:
port: 8082
spring:
application:
name: eureka-client
配置RestTemplate的Bean对象:
package com.jake.eurekaclient.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
记得在启动类上加入@EnableEurekaClient注解。
测试mall-crud项目接口用的控制层:
package com.jake.eurekaclient.controller;
import com.jake.mallmodel.entity.User;
import com.jake.mallmodel.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@RequestMapping("users")
@SuppressWarnings("unchecked")
public class UserController {
@Autowired
private RestTemplate restTemplate;
private static final String MALL_CRUD_USERS_URL = "http://mall-crud/users/";
@GetMapping
public List getUsers() {
List users = restTemplate.getForObject(MALL_CRUD_USERS_URL, List.class);
return users;
}
@GetMapping("info")
public List getAllUserInfo() {
List allUserInfo = restTemplate.getForObject(MALL_CRUD_USERS_URL + "info/", List.class);
return allUserInfo;
}
@GetMapping("{uid}")
public User getUserById(@PathVariable Integer uid) {
User user = restTemplate.getForObject(MALL_CRUD_USERS_URL + uid, User.class);
return user;
}
@GetMapping("info/{uid}")
public UserInfo getUserInfoById(@PathVariable Integer uid) {
UserInfo userInfo = restTemplate.getForObject(MALL_CRUD_USERS_URL + "info/" + uid, UserInfo.class);
return userInfo;
}
@GetMapping("info/{cname}/{username}")
public List getUserInfoByUsernameAndCname(@PathVariable String username, @PathVariable String cname) {
List userInfoList = restTemplate.getForObject(MALL_CRUD_USERS_URL + "info/" + cname + "/" + username, List.class);
return userInfoList;
}
@PostMapping
public String addUser(@RequestBody User user) {
String msg = restTemplate.postForObject(MALL_CRUD_USERS_URL, user, String.class);
return msg;
}
@PutMapping
public void updateUser(@RequestBody User user) {
restTemplate.put(MALL_CRUD_USERS_URL, user);
}
@DeleteMapping("{uid}")
public void deleteUserById(@PathVariable Integer uid) {
restTemplate.delete(MALL_CRUD_USERS_URL + uid);
}
}
其中实体类User来自项目mall-model,从URL可知,此客户端要调用的是mall-crud的RESTFUL接口,获取用户数据。
注:此处有个缺陷:restTemplate的put和delete方法的类型为void,所以访问eureka-client的新增和删除接口没有获取mall-crud接口的提示信息,并返回给前端。
在浏览器中输入:localhost:8081,可进入Eureka Server主页
由页面信息可知,eureka-client(8082)和mall-crud(8083)已注册到Eureka Server,两者可以获取对方的注册信息,并相互访问接口,本文中,我们通过postman测试eureka-client(8082)来访问mall-crud(8083)的CRUD接口。
HTTP请求方式选为GET
localhost:8082/users
localhost:8082/users/info
localhost:8082/users/1
localhost:8082/users/info/admin.com/admin
HTTP请求方式选为POST,请求头选为Content-Type:application/json
localhost:8082/users/
{
"username": "Jason Tang",
"uid": 10
}
HTTP请求方式选为PUT,请求头选为Content-Type:application/json
localhost:8082/users/
{
"username": "Jason.Tang",
"uid": 10
}
HTTP请求方式选为DELETE
localhost:8082/users/10