一.服务提供者创建项目->microservicecloud-provider-dept
1.提供者POM.xml配置
<?xml version="1.0" encoding="UTF-8"?> <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"> <parent> <artifactId>mall</artifactId> <groupId>com.linjia</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microservicecloud-provider-dept</artifactId> <name>microservicecloud-provider-dept</name> <url>http://www.example.com</url> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>com.linjia</groupId> <artifactId>microservicecloud-api</artifactId> <version>${project.version}</version> </dependency> <!-- actuator监控信息完善 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- 将微服务provider侧注册进eureka --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> </dependencies> <build> <finalName>${name}</finalName> <!-- 打包jar名称--> <plugins> <plugin><!-- 打包可运行的jar --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
2.提供者application.yml配置
server: port: 8001 mybatis: config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径 type-aliases-package: com.linjia.springcloud.entity # 所有Entity别名类所在包 mapper-locations: - classpath:mybatis/mapper/*.xml # mapper映射文件 spring: application: name: microservicecloud-dept datasource: type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型 driver-class-name: org.gjt.mm.mysql.Driver # mysql驱动包 url: jdbc:mysql://192.168.0.38:3306/test_1 # 数据库名称 username: root password: linjia dbcp2: min-idle: 5 # 数据库连接池的最小维持连接数 initial-size: 5 # 初始化连接数 max-total: 5 # 最大连接数 max-wait-millis: 200 # 等待连接获取的最大超时时间 jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate.format_sql: true database-platform: org.hibernate.dialect.MySQL5InnoDBDialect eureka: client: service-url: defaultZone: http://localhost:7001/eureka #将客户端注册进eureka服务列表内 # defaultZone: http://localhost:7001/eureka,http://localhost:7002/eureka,http://localhost:7003/eureka instance: instance-id: ${spring.cloud.client.ipAddress}:${server.port} #自定义服务名称信息 启动多个服务做集群需要设置为不同的ID值 prefer-ip-address: true #访问路径可以显示IP地址 info: app.name: microservicecloud-dept company.name: www.baidu.cn build.artifactId: $project.artifactId$ build.version: $project.version$
3.提供者启动类:
package com.linjia; 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; import org.springframework.context.annotation.ComponentScan; /** * Hello world! * */ @SpringBootApplication @ComponentScan("com.linjia.springcloud") @EnableEurekaClient//启动服务注册 @EnableDiscoveryClient public class ProviderApplication { // 集群模式 Terminal or cmd 运行 // E:\mall\microservicecloud-provider-dept\target>java -jar microservicecloud-provider-dept.jar --server.port=8082 public static void main( String[] args ) { SpringApplication.run(ProviderApplication.class, args); } }
4.提供者Controller,dao,service省略
package com.linjia.springcloud.controller; import com.linjia.springcloud.entity.Dept; import com.linjia.springcloud.service.DeptService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @date 2018/5/14 */ @RestController public class DeptController { private static final Logger logger= LoggerFactory.getLogger(DeptController.class); @Autowired private DeptService service; @Autowired private DiscoveryClient client; @RequestMapping(value = "/dept/add", method = RequestMethod.POST) public boolean add(@RequestBody Dept dept) { return service.add(dept); } @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET) public Dept get(@PathVariable("id") Long id) { return service.get(id); } @RequestMapping(value = "/dept/list", method = RequestMethod.GET) public List<Dept> list() { logger.info("springCloud-Ribbon负载均衡测试"); return service.list(); } @GetMapping("/dept/discovery") public Object discovery() { List<String> services = client.getServices(); String description = client.description(); System.out.println("description = " + description); System.out.println("services = " + services); List<ServiceInstance> instances = client.getInstances("microservicecloud-dept"); return client; } }
启动注册中心,eureka,provider,访问:http://localhost:8001/dept/list
二.服务消费者创建项目->microservicecloud-consumer-dept
2.1 消费者POM.xml配置
<?xml version="1.0" encoding="UTF-8"?> <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"> <parent> <artifactId>mall</artifactId> <groupId>com.linjia</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microservicecloud-consumer-dept</artifactId> <name>microservicecloud-consumer-dept</name> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>com.linjia</groupId> <artifactId>microservicecloud-api</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <!-- zipkin --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zipkin</artifactId> </dependency> <!-- eureka相关 eureka与zookeeper区别,zookeeper 高一致性,eureka 高可用--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <!-- 修改后立即生效,热部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <!-- web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <finalName>${name}</finalName> </build> </project>
2.2 application.yml配置
server: port: 80 eureka: client: register-with-eureka: false service-url: defaultZone: http://springCloudEureka7001.com:7001/eureka/ # defaultZone: http://springCloudEureka7001.com:7001/eureka/,http://springCloudEureka7002.com:7002/eureka/,http://springCloudEureka7003.com:7003/eureka/ #集群模式
2.3 启动类
package com.linjia; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.RandomRule; import com.netflix.loadbalancer.RoundRobinRule; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** * Hello world! * */ @SpringBootApplication @EnableEurekaClient //注册中心客户端 @Configuration public class ConsumerApplication { public static void main( String[] args ) { SpringApplication.run(ConsumerApplication.class, args); } @Bean @LoadBalanced //初始化生成bean实例,LoadBalanced 实现负载均衡 先添加Ribbon相关 jar public RestTemplate getRestTemplate() { return new RestTemplate(); } @Bean public IRule myRule(){ //retrun new RetryRule(); 重试策略 ,一个服务挂了,调用失败N次后不再调用失败的服务,重试其它可用的服务(服务都为健康状态下是为轮询算法) return new RoundRobinRule();//轮询算法,默认 // return new RandomRule(); //随机算法 } }
2.4 消费者Controller
package com.linjia.springcloud.web; import com.linjia.springcloud.entity.Dept; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.List; /** * @author * @date 2018/5/14 */ @RestController public class DeptController_Consumer { private static final Logger logger = LoggerFactory.getLogger(DeptController_Consumer.class); //public static final String REST_URL_PREFIX = "http://localhost:7001"; private static final String REST_URL_PREFIX = "http://microservicecloud-dept"; //访问eureka注册中心 @Autowired private RestTemplate restTemplate; /** * 使用 RestTemplate 访问 restful 接口非常的简单粗暴无脑。 * (url, requestMap, ResponseBean.class) 这三个参数分别代表 * REST请求地址、请求参数、HTTP响应被转化成的对象类型 * * @param dept * @return */ @RequestMapping("/consumer/dept/add") public boolean add(Dept dept) { return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class); } @RequestMapping("/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class); } @RequestMapping("/consumer/dept/list") public List<Dept> list() { logger.info("restTemplate:"+1); return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class); } @RequestMapping(value = "/consumer/dept/discovery") public Object discovery() { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/discovery", Object.class); } }
2.5启动项目microservicecloud-consumer-dept
访问:http://localhost/consumer/dept/list