springcloud-服务消费-负载均衡

springcloud 服务消费

在springcloud中,服务的提供者和服务的消费者都需要在注册器中进行注册。

进行注册的应用都需要被注解

可以使用 @EnableEurekaClient 或者 @EnableDiscoveryClient 两者的取别是如果注册中心是eureka的情况下两者都能使用,但如果注册中心不是eureka时,只能使用@EnableDiscoveryClient。即,@EnableDiscoveryClient更加宽泛。

另外一个要注意的是有时候用@SpringBootApplication 容易出404错误,但写

@EnableAutoConfiguration
@ComponentScan(basePackages={"com.anlysqx.*"})

没有出过问题

做了注解后,先启动server再启动client,这样就能被发现。

为了使用服务,需要一个RestTemplate 对象来帮忙。

特别注意的是,要用java配置的方式,手动new 出来一个bean。然后在service中自动注入。

代码如下:

package com.anlysqx.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
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.ComponentScan;
import org.springframework.web.client.RestTemplate;


@EnableAutoConfiguration
@ComponentScan(basePackages={"com.anlysqx.*"})
@EnableEurekaClient
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
	
	@Bean
	@LoadBalanced
	RestTemplate restTemplate(){
		return new RestTemplate();
	}
	
}

另外一个重点是如何使用RestTemplate对象:

package com.anlysqx.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloService {

	@Autowired
	private RestTemplate restTemplate;
	
	public String hi(String name){
		return restTemplate.getForObject("http://service-hi/hi?name="+name, String.class);
	}
	
}

就是调用一个方法而已。但url中域名和端口号要改为在yml文件中写的 name,注意,写成什么样就是什么,大小写敏感

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8763
spring:
  application:
    name: service-hi

负载均衡体现在手动new RestTemplate 对象时加上的一个@LoadBalanced注解

就是当一个应用修改端口号再启动一次,那么在注册中心中就会有一个应用名对应两个运行端口,这时可以均衡地访问这两个端口。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值