-
provider 服务生产者环境的搭建
导入相关依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置yml文件
server:
port: 8001
mybatis:
type-aliases-package: com.fly.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true
spring:
application:
name: springcloud-provider-dept
#数据源配置
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.gjt.mm.mysql.Driver
url: jdbc:mysql://localhost:4001/db01?serverTimeZone=UTC&useUnicode=true&characterEncoding=utf-8
username: *****
password: *******
#eureka配置
eureka:
client:
service-url:
#连接的eureka地址
defaultZone: http://localhost:7001/eureka
instance:
instance-id: springcloud-privider-dept-8001
info:
app.name: zhu
company.name: zhu
编写主启动类
@SpringBootApplication
@EnableEurekaClient //开启eureka客户端配置
//@EnableCircuitBreaker
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
-
consumer服务消费者的搭建
##服务的搭建和配置和生产者一致##
调用方式:Ribbon 和 Feign 两种
导入ribbon相关的依赖
<!-- ribbon -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
Ribbon调用方式:
//编写RestTemplate配置,并配置负载均衡机制默认是轮询(这样可以直接通过服务名去调用)
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
//调用示例:
@RestController
public class DeptConsumerController {
@Resource
private RestTemplate restTemplate;
@Resource
private DiscoveryClient client;
//服务的生产者的服务名
private static final String REST_URL_PREFIX = "http://springcloud-provider-dept";
@GetMapping("/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id) {
Dept dept = restTemplate.getForObject(REST_URL_PREFIX + "/dept/getById?id=" + id, Dept.class);
return dept;
}
}
Feign 调用方式:
Feign 调用方式更能体现面向接口编程的思想
//主启动类中需要开启Feign相关的配置
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.fly"})
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
//1. 编写一个服务调用的接口
@Component
//指定要调用的服务端的服务名称
@FeignClient(value = "springcloud-provider-dept")
public interface DeptService {
@GetMapping("/dept/getById")
public Dept queryDeptById(Long id);
@GetMapping("/dept/list")
public List<Dept> queryAll();
}
//按照接口的方式直接调用
@RestController
public class DeptConsumerController {
@Resource
private DeptService deptService;
@GetMapping("/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id) {
return deptService.queryDeptById(id);
}
@GetMapping("/consumer/dept/list")
public List<Dept> list() {
return deptService.queryAll();
}
}