四、 在高可用的 Eureka 注册中心中构建 provider 服务
1 创建项目
2 修改 pom 文件
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
3 修改启动类----@EnableEurekaClient
package com.kennosaur;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class EurekaproviderApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaproviderApplication.class, args);
}
}
4 修改 provider 的配置文件
spring.application.name=eureka-provider
server.port=9090
#设置服务注册中心地址,指向另一个注册中心
eureka.client.serviceUrl.defaultZone=http://eureka1:8761/eu
reka/,http://eureka2:8761/eureka/
5 修改 windows 的 host 文件-----路径:C:\Windows\System32\drivers\etc
192.168.70.134 eureka1
192.168.70.135 eureka2
6 编写服务接口
6.1创建接口
package com.kennosaur.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.kennosaur.pojo.User;
@RestController
public class UserController {
@RequestMapping("/user")
public List<User> getUsers(){
List<User> list = new ArrayList<>();
list.add(new User(1,"zhangsan",20));
list.add(new User(2,"lisi",22));
list.add(new User(3,"wangwu",20));
return list;
}
}
6.2创建 pojo
package com.kennosaur.pojo;
public class User {
private int userid;
private String username;
private int userage;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserage() {
return userage;
}
public void setUserage(int userage) {
this.userage = userage;
}
public User(int userid, String username, int userage) {
super();
this.userid = userid;
this.username = username;
this.userage = userage;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
}
五、 在高可用的 Eureka 注册中心中构建 consumer 服务
1 创建项目
服务的消费者与提供者都需要再 Eureka 注册中心注册
2 Consumer 的配置文件
spring.application.name=eureka-consumer
server.port=9091
#设置服务注册中心地址,指向另一个注册中心
eureka.client.serviceUrl.defaultZone=http://eureka1:8761/eu
reka/,http://eureka2:8761/eureka/
3 在 Service 中完成服务的调用
package com.kennosaur.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.kennosaur.pojo.User;
@Service
public class UserService {
@Autowired
private LoadBalancerClient loadBalancerClient;//ribbon 负载均衡器
public List<User> getUsers(){
//选择调用的服务的名称
//ServiceInstance 封装了服务的基本信息,如 IP,端口
ServiceInstance si = this.loadBalancerClient.choose("eureka-provider");
//拼接访问服务的 URL
StringBuffer sb = new StringBuffer();
//http://localhost:9090/user
sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/user");
//springMVC RestTemplate
RestTemplate rt = new RestTemplate();
ParameterizedTypeReference<List<User>> type = new ParameterizedTypeReference<List<User>>() {};
//ResponseEntity:封装了返回值信息
ResponseEntity<List<User>> response =rt.exchange(sb.toString(),HttpMethod.GET, null, type);
List<User> list =response.getBody();
return list;
}
}
4 Controller
package com.kennosaur.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.kennosaur.pojo.User;
import com.kennosaur.service.UserService;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/consumer")
public List<User> getUsers(){
return this.userService.getUsers();
}
}
六、 Eureka 注册中心架构原理
1 Eureka 架构图
七、 基于分布式 CAP 定理,分析注册中心两大主流框架:Eureka与 Zookeeper 的区别
2 Zookeeper 与 Eureka 的区别
八、 Eureka 优雅停服
1 在什么条件下,Eureka 会启动自我保护?
2 为什么要启动自我保护
3 如何关闭自我保护
修改 Eureka Server 配置文件
#关闭自我保护:true 为开启自我保护,false 为关闭自我保护
eureka.server.enableSelfPreservation=false
#清理间隔(单位:毫秒,默认是 60*1000)
eureka.server.eviction.interval-timer-in-ms=60000
4 如何优雅停服
4.1不需要再 Eureka Server 中配置关闭自我保护
4.2需要在服务中添加 actuator.jar 包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
4.3修改配置文件
#启用 shutdown
endpoints.shutdown.enabled=true
#禁用密码验证
endpoints.shutdown.sensitive=false
4.4发送一个关闭服务的 URL 请求-----只能通过Post方式请求,不能通过Get方式请求
package com.bjsxt.springboothelloworld;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
public static void main(String[] args) {
String url ="http://127.0.0.1:9090/shutdown";
//该url必须要使用dopost方式来发送
HttpClientUtil.doPost(url);
}
}
九、 如何加强 Eureka 注册中心的安全认证
1 在 Eureka Server 中添加 security 包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2 修改 Eureka Server 配置文件
#开启 http basic 的安全认证
security.basic.enabled=true
security.user.name=user
security.user.password=123456
3 修改访问集群节点的 url---------user:123456@
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka2:8761/eureka/
4 修改微服务的配置文件添加访问注册中心的用户名与密码
spring.application.name=eureka-provider
server.port=9090
#设置服务注册中心地址,指向另一个注册中心
eureka.client.serviceUrl.defaultZone=http://user:123456@eur
eka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
#启用 shutdown
endpoints.shutdown.enabled=true
#禁用密码验证
endpoints.shutdown.sensitive=false