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