您的位置:首页 > 编程语言 > Java开发

springCloud的注册中心eureka

2018-03-07 00:00 471 查看

1、服务端启动

1、配置文件

application.yml

info:
app:
name: 注册中心服务器
version: 1.0.0-SNAPSHOT

server:
port:1111
tomcat:
max-threads: 1000
uri-encoding: UTF-8

spring:
profiles:
active: dev
application:
name: pluto-cerberus
http:
encoding:
charset: UTF-8
force: true

eureka:
client:
register-with-eureka: true
fetch-registry: true
serviceUrl:
defaultZone: "http://peer1:1111/eureka/,http://peer2:1111/eureka/,http://peer3:1111/eureka/"
server:
# 清理间隔(单位毫秒,默认是60*1000)
eviction-interval-timer-in-ms: 5000
enable-self-preservation: false

启动类:

@EnableEurekaServer
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}

@EnableEurekaServer 服务端启动注解

2、客户端启动

@EnableEurekaClient
//启动EnableEureka客户端


SpringCLoud中的“Discovery Service”有多种实现,比如:eureka, consul, zookeeper。

1,
@EnableDiscoveryClient
注解是基于
spring-cloud-commons
依赖,并且在classpath中实现;
2,
@EnableEurekaClient
注解是基于
spring-cloud-netflix
依赖,只能为eureka作用;

如果你的classpath中添加了eureka,则它们的作用是一样的。

2、客户端配置文件

application.yml配置

1
2
3
4
5
6
7
8
9
10
11
12
server:

port:
8081
#
8181

spring:

application:

name: microservice-provider-user

eureka:

client:

serviceUrl:

defaultZone: http:
//user:123456@localhost:8761/eureka#注册 中心已经开启认证

instance:

prefer-ip-address:
true

instanceId: ${spring.application.name}:${spring.application.instance_id:${server.port}}

客户端启动注解:

@EnableFeignClients微服务之间的调用

微服务 通过EnableFeignClients调用其他服务的api

今天在项目上遇到一个问题,通过当前service服务要调用到其他service服务的api接口时,可通过EnableFeignClients调用其他服务的api,大概的步骤如下:

1、在springboot的main处加上注解@EnableFeignClients



1 @EnableDiscoveryClient
2 @SpringBootApplication
3 @EnableFeignClients
4 public class DeploymentServiceApplication {
5
6 public static void main(String[] args){
7 SpringApplication.run(DeploymentServiceApplication.class, args);
8 }
9
10 }




2、在service层上实现接口,这里注意value可以用serviceId代替,但是最好用value来指定要调用的服务。

fallback是当程序错误的时候来回调的方法

方法中要用@PathVariable要注解参数

1 @FeignClient(value = "hap-user-admin-service", fallback = OrganizationLabelFeignClientFallback.class)
2 public interface OrganizationLabelFeignClient {
3 @RequestMapping(value = "/v1/organizations/{id}",method = RequestMethod.GET)
4 Organization queryOrgLabel(@PathVariable(name="id") Long id);
5 }


3、编写程序错误时的回调类,实现接口,在错误时回调



1 @Service
2 public class OrganizationLabelFeignClientFallback implements OrganizationLabelFeignClient {
3 @Override
4 public Organization queryOrgLabel(Long id) {
5 return null;
6 }
7 }




4、调用该服务



1 //声明,自动封装
2 @Autowired
3 private OrganizationLabelFeignClient organizationLabelFeignClient;
4
5
6 //调用
7 Organization organization = organizationLabelFeignClient.queryOrgLabel(organizationId);


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息