一: 首先搭建一个服务的注册中心
1.
2.在启动类上打上注解:
@EnableEurekaServer
3.在application.yml配置文件中加上配置信息
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
#由于该应用为注册中心,所以设置为false,代表不向注册中心注册自己
registerWithEureka: false
#由于注册中心的职责就是维护服务实例,它并不需要去检索服务,所以也设置为false
fetchRegistry: false
serviceUrl:
#默认的命名空间,代表的是注册中心的地址
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
4.启动,访问注册中心页面,可以看到服务的提供者和消费者的信息
http://localhost:8761
二:服务注册和服务的发现Eureka-client,服务的提供者
1.
2.在applicaiton.yml配置文件中添加配置信息,指定注册中心的地址和向注册中心注册自己的服务
eureka:
client:
serviceUrl:
#指定注册中心的地址
defaultZone: http://localhost:8761/eureka/
server:
port: 8771
spring:
application:
name: product-service
三:服务注册和服务的发现Eureka-client,服务的消费者,
方式一:通过ribbon调用服务,ribbon(类似httpclient,URLConnection)
方式二:通过feign调用服务,就像在本地服务的服务一样调用
1.
2.在application.yml中增加配置文件信息
server:
port: 8781
spring:
application:
name: order-service
eureka:
client:
serviceUrl:
#指定注册中心的地址
defaultZone: http://localhost:8761/eureka/
#自定义负载均衡策略,默认是轮询策略,可以配置权重等等
product-service:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
3.在配置类中添加注解,客户端实现软负载均衡,通过spring的restemplate调用服务
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
//方式一:使用ribbon调用远程服务,本质是一个http调用,地址是服务提供者的服务名称和路由路径
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/createOrder")
public String createOrder(@RequestParam("order_id")Long orderId){
//调用的地址是服务提供者的地址
String response = restTemplate.getForObject("http://product-service/findProductById?id="+orderId, String.class);
return response;
}
4.方式二:通过feign调用服务,本质还是http
在启动类上加上注解,@EnableFeignClients
5.创建一个接口,
//这里需要指定服务提供者的名称
@FeignClient(value = "product-service")
public interface ProductService {
@RequestMapping("/findProductById")
String findProductById(@RequestParam(value = "id") int id);
}
注意:路径要和服务提供者的路径一致,调用方法一致,多参数时,使用@RequestParam(“id” int id)方式调用
Feign和ribbon的关系,
1.feign默认集成了ribbon,写起来更加方便,采用注解方式进行配置,配置熔断等方式方便
2.超时时间配置,hystrix默认是1秒超时
修改调用超时时间
feign:
client:
config:
default:
connectTimeout: 2000
readTimeout: 2000