【微服务——Eureka注册中心实践】搭建教程及服务调用&&负载均衡

eureka注册中心实践

搭建EurekaServer

【1】引入spring-cloud-starter-netflix-eureka-server依赖

<dependency>
	<groupId>org.springframework.cloudgroupId>
	<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>

[2]配置启动类

@SpringBootApplication
//引入注解
@EnableEurekaServer
public class EurekaApplication(String[] args){
    SpringApplication.run(EurekaApplication.class,args);
}

【3】设置application.yml文件

eureka自己也是一个微服务,需要注册到eureka上

server:
	port:10086
spring:
	application:
		name:eurekaserver # 服务名称
eureka:
	client:
		service-url: # eureka地址信息
			defaultZone:http://127.0.0.1:10086/eureka

【4】启动eureka

输入url(http://127.0.0.1:10086/eureka)即可跳转显示eureka信息


服务间调用

服务1注册到Eureka

【1】引入依赖

<dependency>    
    <groupId>org.springframework.cloudgroupId>    
    <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>

【2】配置yml文件(注册)

server:
	port:8080
spring:
	application:
		name:service1 # 服务名称
		。。。。
。。。。
。。。。
eureka:
	client:
		service-url: # eureka地址信息
			defaultZone:http://127.0.0.1:10086/eureka
服务2完成服务1的拉取

【1】服务2在service层进行修改,因为注册中心保存了服务名称与其对应的端口地址,所以这里把url改为服务名称。

@Service
public class service1{
    @Autowired
    private RestTemplate restTemplate;
    ....
    public Dao1 queryDao1ById(Long Dao1Id){
        ...
        // String url = "http://127.0.0.1:8080/Application2/"+dao1.getDao2Id();
        //修改为:
           String url = "http://service1/Application1/"+dao1.getDao2Id();  
        //发起http请求,实现远程调用,可以自动将json反序列化为对象
        Dao2 dao2 = restTemplate.getForObject(url,Dao2.class);
        dao1.setDao2(dao2);
        return dao1;
    }
}

【2】在服务2的启动类加上负载均衡注解 @LoadBalanced

@MapperScan(...)
@SpringBootApplication
public class Application2{
    public static void main(){...}
    
    @Bean
    //加入注解
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate;
    }
    
}

【3】通过服务名称进行远程调用

运行服务,通过日志可看到自动进行了负载均衡。

你可能感兴趣的:(微服务,eureka,微服务,负载均衡)