SpringCloud整合Eureka

1.新建Maven父工程Server
(1)导入依赖


        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Dalston.SR5
                pom
                import
            
        
    
    
        
            junit
            junit
            4.11
            test
        

        
            javax.persistence
            persistence-api
            1.0
        
        
            slf4j-api
            org.slf4j
            1.7.10
        
        
            ch.qos.logback
            logback-classic
            1.2.3
            
                
                    slf4j-api
                    org.slf4j
                
            
        
        
            ch.qos.logback
            logback-core
            1.2.3
        

        
            org.springframework.cloud
            spring-cloud-starter-config
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka-server
        
    

(2)创建启动类

@SpringBootApplication
@EnableEurekaServer
public class ServerApplication {
    public static void main(String[] args){
        new SpringApplicationBuilder(ServerApplication.class).web(true).run(args);
    }
}

(3)创建application.yml

server:
  port: 8281
eureka:
  client:
    register-with-eureka: false #服务器不用注册到其他服务器
    fetch-registry: false #服务器不用去服务器抓取注册信息

(4)启动项目运行,访问http://localhost:8281
SpringCloud整合Eureka_第1张图片

2.新建Spring子工程Provider
SpringCloud整合Eureka_第2张图片
SpringCloud整合Eureka_第3张图片
SpringCloud整合Eureka_第4张图片
SpringCloud整合Eureka_第5张图片
(1)新建控制类

@RestController
public class ProviderController {
    @RequestMapping(value = "/provider")
    public String provider(){
        return "==============provider==============";
    }
}

(2)新建application.yml

server:
  port: 8080
spring:
  application:
    name: provider1  #服务提供者名字
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8281/eureka/  #注册到服务器

(3)启动项目运行,访问http://localhost:8281
SpringCloud整合Eureka_第6张图片
3.新建spring子工程Consumer
(1)添加依赖

    
			org.springframework.cloud
			spring-cloud-starter-ribbon
	

(2)新建控制类

@Controller
@Configuration
public class ConsumerController {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @RequestMapping(value = "/consumer")
    @ResponseBody
    public String call(){
        RestTemplate restTemplate = getRestTemplate();
        return restTemplate.getForObject("http://provider1/provider" ,String.class);
    }
}

(3)新建application.yml

server:
  port: 8081 #更改端口为8081
spring:
  application:
    name: consumer1
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/  #注册到服务器

(4)运行项目,访问http://localhost:8081/consumer ,获得返回结果
刷新http://localhost:8281/
SpringCloud整合Eureka_第7张图片
4.源码地址:https://gitee.com/Alisa_zmx/spring-cloud-eureka

你可能感兴趣的:(Spring,Cloud,Eureka)