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

SpringCloud的服务注册与发现Eureka

2017-10-18 10:05 681 查看

服务注册中心

所有的服务端以及访问服务的客户端都需要先连接到eureka服务器。在启动服务的时候会自动注册到eureka服务器。每一个服务都有自己的名字,在配置文件中设置的,这个名字会被注册到eureka服务器,使用服务的一方只需要名字加上方法名就可以调用到该服务。

#应用名,服务名,如果不指定就是unkown
spring.application.name=eureka-server


在默认的设置下,在启动服务的时候,服务注册中心也会把自己当成服务注册给自己,所以需要禁用它的这种客户端注册的行为

eureka.client.register-with-eureka=false


#是否需要去检索寻找服务,默认是true  是否从eureka服务器获取注册信息
eureka.client.fetch-registry=false
#指定端口号
server.port=1111


在主类中使用注解@EnableEurekaServer就可以让应用变为erueka服务器。主类的信息:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}


配置文件的信息:

#应用名,服务名,如果不指定就是unkown
spring.application.name=eureka-server
#实例的主机名
server.port=1001
eureka.instance.hostname=localhost
#设置是否向注册中心注册,默认是true
eureka.client.register-with-eureka=false
#是否需要去检索寻找服务,默认是true
eureka.client.fetch-registry=false


启动服务访问localhost:1001即可看到如下界面:



如果想要服务使用Eureka服务器,那么需要新建一个服务。我把它命名为

computer-service:



在服务的java里面可以新建一个web包 用来写controller 或者说是逻辑代码,在类里面需要创建DiscoveryClient类的实体



通过DiscoveryClient对象,在日志中打印出服务实例的相关内容。computerController代码如下:

/**
* Created by YHS on 2017/9/15.
*/
@RestController
public class ComputerController {
private final Logger logger = Logger.getLogger(String.valueOf(getClass()));
@Autowired
private DiscoveryClient client;
@RequestMapping(value = "/add" ,method = RequestMethod.GET)
public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
ServiceInstance instance = client.getLocalServiceInstance();
Integer r = a + b;
logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
return r;
}
}


最后在主类中通过加上@EnableDiscoveryClient注解,该注解能激活Eureka中的DiscoveryClient实现,才能实现Controller中对服务信息的输出。

@EnableDiscoveryClient
@SpringBootApplication
public class ComputerServiceApplication {

public static void main(String[] args) {

SpringApplication.run(ComputerServiceApplication.class, args);
}
}


然后配置application.properties配置信息:

#服务名字
spring.application.name=computer-service1
#服务端口号
server.port=1111
#指定注册中心的位置
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/


启动该工程,然后访问http://localhost:1001,可以看到新建的这个computer服务已经被注册。

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