springcloud(二) eureka的使用
上一节讲到order微服务是通过rest调用user微服务的地址。但是,user微服务的地址是写死的, 如果user微服务集群的话,那么order微服务该如何调用呢?这个时候注册中心该上场了
演示eureka的使用:
pom.xml:
<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> <groupId>com.tuling.springcloud</groupId>
<artifactId>04-eureka-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>04-eureka-server</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- eureka server 注册中心依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency> <!-- 安全模块与属性文件配合使用 -->
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties:
server.port=8761 #取消向eureka server(注册中心)注册,因为现在一台eureka,所以不需要把自己注册到别的eureka上,集群的时候就要改为true
eureka.client.register-with-eureka=false #取消向eureka server(注册中心)获取注册信息,因为现在一台eureka,所以不需要同步其他rureka的数据,集群的时候就要改为true
eureka.client.fetch-registry=false #eureka 提供服务发现的地址,注册中心地址
#打开安全模块,当访问http://localhost:8761/eureka的时候就需要输入帐号和密码
#eureka.client.service-url.defaultZone=http://likehow:777@localhost:8761/eureka
eureka.client.service-url.defaultZone=http://localhost:8761/eureka # 安全模块,要添加maven依赖,
#security.basic.enabled=true #是否打开
#security.user.name=likehow #帐号
#security.user.password=777 #密码
EurekaServerStart.java:
package com.tuling.springcloud; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication
@EnableEurekaServer //作为EurekaServer注册中心,服务提供者如果挂机,它的URL将会在eureka存活90s,如果还没连接上就清除url
public class EurekaServerStart { // http://localhost:8761
public static void main(String[] args) throws Exception {
SpringApplication.run(EurekaServerStart.class, args);
}
}
- @EnableEurekaServer:开启Eureka Server ,表示这个应用是注册中心,服务提供者如果挂机,它的URL将会在eureka存活90s,如果还没连接上就清除url
启动之后:
恭喜你eureka 启动成功。
接下来使用 user微服务和order微服务和eureka 一起使用:
order微服务结构
pom.xml:
<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> <groupId>com.tuling.springcloud</groupId>
<artifactId>04-microservice-order</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>04-microservice-order</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <dependencies>
<!-- 此包包含了eurekaclient,ribbon-->
<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>
<!-- Spring WEB -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 集成Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
OrderController:
package com.tuling.springcloud.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import java.util.HashMap;
import java.util.Map; @RestController
@RequestMapping("/order")
public class OrderController {
private final Logger logger = LoggerFactory.getLogger(OrderController.class); @Autowired
private RestTemplate restTemplate; @RequestMapping("")
public Object testHttp() {
Map<String , Object> map = new HashMap<String,Object>();
map.put("result","success");
return map;
} //http://localhost:8082/order/user/getById?userId=1
@RequestMapping("/user/getById")
public Object getUserById(String userId) {
String url = "http://localhost:8081/user/getById?id=" + userId;
logger.debug("param userId : {}, request url : {}", userId, url);
Object result = restTemplate.getForEntity(url, Object.class);
return result;
} @RequestMapping("/user/getByIdEureka")
public Object getUserByIdEureka(String userId) {
// 注意这里的IP换成了应用名称,order回去注册中心获取microservice-user提供者列表然后进行调用
String url = "http://microservice-user/user/getById?id=" + userId;
Object result = restTemplate.getForEntity(url, Object.class);
return result;
} }
CommonConfig:
package com.tuling.springcloud.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 CommonConfig { /*@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}*/ @Bean
@LoadBalanced //轮询调用,作用是负载均衡,注意这个负载均衡的代码一定是写在调用方
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
application.properties:
spring.application.name=microservice-order
# 假设服务的调用者以80开头
server.port=8082
## db config
spring.datasource.url=jdbc:mysql://localhost:3306/springcloud
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver ## log
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
logging.level.com.tuling.springcloud=DEBUG eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
#如果eureka开了安全模式,那么注册的时候也要换地址
#eureka.client.serviceUrl.defaultZone=http://zhangfei:777@localhost:8761/eureka #是否显示ip地址
eureka.instance.prefer-ip-address=true
#微服务实例显示的格式
eureka.instance.instance-id=${spring.application.name}:${spring.application.instance_id:${server.port}}
order微服务结构:
pom.xml:
<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> <groupId>com.tuling.springcloud</groupId>
<artifactId>04-microservice-user</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>04-microservice-user</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- 此包包含了eurekaclient,ribbon-->
<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>
<!-- Spring WEB -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 集成Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
UserController:
package com.tuling.springcloud.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.tuling.springcloud.bean.User;
import com.tuling.springcloud.service.UserService; @RestController
@RequestMapping("/user")
public class UserController {
private final Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired
private UserService userService; @Autowired
private Registration registration; @RequestMapping("/getById")
public User getUserById(String id) {
logger.debug("param id : {}", id);
logger.info("远程IP和端口 :{}" , registration.getHost() + ":" + registration.getPort());
return this.userService.findById(Integer.parseInt(id));
} }
UserService:
package com.tuling.springcloud.service; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.tuling.springcloud.bean.User;
import com.tuling.springcloud.mapper.UserMapper; @Service
public class UserService {
private final Logger logger = LoggerFactory.getLogger(UserService.class); @Autowired
private UserMapper userMapper; public User findById(Integer id){
logger.debug("param id : {}" , id);
User u = this.userMapper.findById(id);
logger.debug("result name : {}" , u.getName());
return u;
}
}
UserMapper:
package com.tuling.springcloud.mapper; import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import com.tuling.springcloud.bean.User; @Mapper
public interface UserMapper {
/**根据id查询用户*/
@Select("SELECT * FROM T_USER WHERE ID = #{id}")
User findById(@Param("id") Integer id);
/**新增用户*/
@Insert("INSERT INTO T_USER(NAME, AGE, ADDRESS, PHONE) VALUES(#{name}, #{age}, #{address}, #{phone})")
int insert(@Param("name") String name, @Param("age") Integer age,@Param("address") String address,@Param("phone") String phone);
}
启动类UserMicroStart:
package com.tuling.springcloud; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication
@EnableDiscoveryClient
//@EnableEurekaClient
public class UserMicroStart { public static void main(String[] args) throws Exception {
SpringApplication.run(UserMicroStart.class, args);
}
}
// @EnableDiscoveryClient和@EnableEurekaClient效果一样,他们是父子关系
User.java :
package com.tuling.springcloud.bean;
public class User {
private Integer id;
private String name;
private Integer age;
private String address;
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
} }
application.properties:
spring.application.name=microservice-user
# 假设服务的提供者以90开头
server.port=9090
## db config
spring.datasource.url=jdbc:mysql://localhost:3306/springcloud
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver ## log
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
logging.level.com.tuling.springcloud=DEBUG eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
#eureka.client.serviceUrl.defaultZone=http://zhangfei:777@localhost:8761/eureka
#是否显示ip地址
eureka.instance.prefer-ip-address=true
#微服务实例显示的格式
eureka.instance.instance-id=${spring.application.name}:${spring.application.instance_id:${server.port}}
分别启动order,user,eureka, 在修改成user服务的applciation.properties的端口并启动。结果是这样:
然后就可以访问http://localhost:8082/order/user/getByIdEureka?userId=1 。 可以通过控制台看到user服务是被轮询调用的。
欢迎来QQ群:592495675 一起研究 java技术,群里技术大佬,还有所有springCloud 学习源代码
springcloud(二) eureka的使用的更多相关文章
- 浅谈SpringCloud (二) Eureka服务发现组件
上面学习到了如何由一个程序访问另一个程序,那么如果使用SpringCloud来进行访问,该如何访问呐? 可以借助Eureka服务发现组件进行访问. 可以借助官方文档:https://spring.io ...
- SpringCloud(二) - Eureka注册中心,feign远程调用,hystrix降级和熔断
1.项目模块介绍 2. 父项目 主要依赖 spring-cloud 的 版本控制 <properties> <!-- springCloud 版本 --> <scd.ve ...
- 十六、springcloud(二)Eureka集群
1.创建子工程spring-cloud-peer(jar) 2.创建application-peer1.properties,application-peer2.properties applicat ...
- SpringCloud(二)Eureka集群与Feign
两个Eureka 上一篇是两个服务像一个Eureka注册,如果Eureka宕掉了就不好了,现在来搭建两个Eureka,两个服务分别像其注册.两个Eureka都用本机来模拟,用两个端口号来表示. 首先修 ...
- SpringCloud之Eureka服务注册与发现(一)
一 Eureka的基本架构 Spring Cloud 封装了 Netflix 公司开发的 Eureka 模块来实现服务注册和发现(请对比Zookeeper). Eureka 采用了 C-S 的设计架构 ...
- SpringCloud之Eureka:集群搭建
上篇文章<SpringCloud之Eureka:服务发布与调用例子>实现了一个简单例子,这次对其进行改造,运行两个服务器实例.两个服务提供者实例,服务调用者请求服务,使其可以进行集群部署. ...
- SpringCloud中eureka配置心跳和剔除下线的服务的时间
在默认的springCloud中eureka注册中心在服务下线时表现的非常不灵敏,用惯了dubbo的zk注册中心表示很不习惯,eureka设计的本意是在服务不会频繁上下线和网络稳定的内网,这种设计在生 ...
- spring-cloud配置eureka客户端
spring-cloud配置eureka客户端 eureka用来发现其他程序 需要提前配置eureka服务端,具体看 https://www.cnblogs.com/ye-hcj/p/10292944 ...
- SpringCloud学习笔记(三、SpringCloud Netflix Eureka)
目录: 服务发现简介 SpringCloud Netflix Eureka应用 Eureka高可用 Eureka源码分析 >>> Eureka Client初始化(客户端定时获取服务 ...
随机推荐
- Xcode 在读写上提速100倍
- Jmter安装和配置
一.安装JDK 安装JDK 选择安装目录 安装过程中会出现两次安装提示 .第一次是安装 jdk ,第二次是安装 jre .建议两个都安装在同一个java文件夹中的不同文件夹中.(不能都安装在java文 ...
- 用vue实现百度搜索功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Mongodb中在已有Colloection插入/更新相关域值
[{ "confident" : "no", "score" : 0.327355, "label" : "/ ...
- JAVA多线程----用--取钱问题1
“生产者-消费者”模型,也就是生产者线程只负责生产,消费者线程只负责消费,在消费者发现无内容可消费时则睡觉.下面举一个比较实际的例子——生活费问题. 生 活费问题是这样的:学生每月都需要生活费,家长一 ...
- 使用django搭建博客并部署
2017/8/31 18:27:59 为了以后参考的方便,在这里总结一下django搭建博客网站的主要步骤.以下大部分的内容,参考自Django中文文档 - 看云. 需要强调的是,这里使用的djang ...
- BZOJ4974:[Lydsy1708月赛]字符串大师(逆模拟KMP)
题目描述 一个串T是S的循环节,当且仅当存在正整数k,使得S是T k Tk (即T重复k次)的前缀,比如abcd是abcdabcdab的循环节.给定一个长度为n的仅由小写字符构成的字符串S,请对于每 ...
- selenium python实例脚本1
#!/usr/local/bin/python3 # coding=utf-8 #统一编码from selenium import webdriverfrom time import sleep#im ...
- Scala的=>作用
举例: var increase = (x: Int) => x + 1 increase(10) res0: Int = 11 类似于转化符号,=>指明这个函数把左边的东西(任何整数x) ...
- Sprint第一个冲刺(第七天)
今天休息. 燃尽图: