1
2注册中心配置如下:
server: port: 2020 eureka: instance: hostname: localhost client: fetch-registry: false register-with-eureka: false service-url: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
3服务消费者配置如下:
server: port: 8082 spring: application: name: demo_web eureka: client: fetch-registry: true #是否从eureka服务器获取各个微服务地址 register-with-eureka: true #是否注册到eureka服务器 service-url: defaultZone: http://localhost:2020/eureka/
controller如下:
@RestController @RequestMapping("user") public class UserController { @Autowired private UserService userService; @RequestMapping("getUserInfo") public String getUserInfo(String account, String pwd) { System.out.println("服务调用者demo_web="+account); return userService.getUserInfo(account, pwd); } }
Service如下:
@Service public class UserService { @Autowired private RestTemplate restTemplate; public String getUserInfo(String account,String pwd) { System.out.println("执行demo的service方法"); //通过服务提供者的应用名称进行访问 return restTemplate.getForObject("http://USER-CLIENT/adminControl/getJsp?account="+account+"&pwd="+pwd, String.class); } }
Application如下:
@SpringBootApplication @EnableEurekaClient public class DemoWebApplication { @Bean @LoadBalanced public RestTemplate restTemplate() { System.out.println("执行demoweb的restTemplate"); return new RestTemplate(); } public static void main(String[] args) { System.out.println("执行demoweb的main方法"); SpringApplication.run(DemoWebApplication.class, args); } }
3、两个服务提供者的内容完全一致,只是配置的端口不一致:(一个8080,一个8085)
server: port: 8080 spring: datasource: driver-class-name: com.mysql.jdbc.Driver username: root password: root type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://localhost:3306/jx191222 application: name: user-client mybatis: mapper-locations: classpath:mapper/*.xml config-location: classpath:SqlMapConfig.xml eureka: client: fetch-registry: true #是否从eureka服务器获取各个微服务地址 register-with-eureka: true #是否注册到eureka服务器 service-url: defaultZone: http://localhost:2020/eureka
4、打开注册中心:
5、打开服务消费者端口:
6、好像是内部的时间策略机制会自动分配访问哪个端口,实现负载平衡: