eureka简单实例

eureka中,eureka server集群保存客户端信息,客户端获取服务信息、并实现负载均衡。客户端包括:服务调用端(consumer),服务提供端(provider)。

1、eureka server:start.spring.io下新建工程

eureka简单实例_第1张图片

application配置

server.port = 9090
spring.application.name = eureka.server
#取消服务器自我注册
eureka.client.register-with-eureka=false
eureka.client.fetch-register=false
#用于客户端注册。
eureka.client.serviceUrl.defaultZone= \
  http://localhost:${server.port}/eureka
management.security.enabled = false

引导类ServerApplication

@SpringBootApplication
@EnableEurekaServer
public class ServerApplication {

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

}

2、eureka client:start.spring.io下新建工程

eureka简单实例_第2张图片

provider application配置

server.port = 8080

spring.application.name = eureka-user-provider
eureka.server.port = 9090

#取消服务器自我注册
#eureka.client.register-with-eureka=false
#eureka.client.fetch-register=false

#用于客户端注册。
eureka.client.serviceUrl.defaultZone= \
  http://localhost:${eureka.server.port}/eureka
management.security.enabled = false

provider端controller通过restTemplate调用

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping(path = "/save")
    public boolean save(@RequestBody User user){
        System.out.println("save" + user.toString());
        userService.save(user);
        return true;
    }

    @GetMapping(path = "/list")
    public Collection list(){
        System.out.println("list");
        return userService.list();
    }
}
@SpringBootApplication
@EnableEurekaClient
public class BootStrap {
    public static void main(String[] args) {
        SpringApplication.run(BootStrap.class, args);
    }
}

consumer端application配置

server.port = 7070
spring.application.name = eureka-user-consumer
eureka.server.port = 9090
#取消服务器自我注册
#eureka.client.register-with-eureka=false
#eureka.client.fetch-register=false
#用于客户端注册。
eureka.client.serviceUrl.defaultZone= \
  http://localhost:${eureka.server.port}/eureka
management.security.enabled = false

consumer端通过restTemplate调用provider端controller

@Service
public class UserServiceProxy implements UserService {
    private final String URL_PREX = "http://eureka-user-provider";
    @Autowired
    RestTemplate restTemplate;
    @Override
    public Boolean save(User user) {
        System.out.println("web:save");
        return restTemplate.postForObject(URL_PREX + "/save", user, Boolean.class);
    }

    @Override
    public Collection list() {
        System.out.println("web:list");
        return restTemplate.getForObject(URL_PREX + "/list", Collection.class);
    }
}
@SpringBootApplication
@EnableEurekaClient
public class ConsumerBootStrap {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerBootStrap.class, args);
    }

    @LoadBalanced
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

你可能感兴趣的:(spring,cloud)