上一节讲到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 学习源代码