一直想写springcloud的搭建教程,今天就来整理一下吧。
#eureka注册中心
server:
port: 8761 #端口号
eureka:
instance:
hostname: localhost
client:
#表示十分将自己注册到Eureka Server,默认为true。由于当前应用就是Eureka Server,故而设为false。
register-with-eureka: false
#表示是否从Eureka Server获取注册信息,默认为true。因为这是一个单点的Eureka Server,不需要同步其他 的Eureka Server节点的数据,故而设为false
fetch-registry: false
#置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址,默认是http://localhost:8761/eureka;多个地址可用,分隔
service-url:
default-zone: http://${eureka.instance.hostname}:${server.port}/eureka/
@EnableEurekaServer是声明这是一个Eureka注册中心
@EnableEurekaServer
@SpringBootApplication
public class ServerCenterApplication {
public static void main(String[] args) {
SpringApplication.run(ServerCenterApplication.class, args);
}
}
如上图所示,看到没有任何的服务提供者。
构建方式和上面一样,就不再赘述了。
#eureka-client
#端口号
server:
port: 8082
eureka:
instance:
hostname: localhost
#置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址,默认是http://localhost:8761/eureka;多个地址可用,分隔
client:
service-url:
default-zone: http://localhost:8761/eureka/
spring:
application:
name: service-order
@EnableEurekaClient
@SpringBootApplication
public class ServerOrderApplication {
public static void main(String[] args) {
SpringApplication.run(ServerOrderApplication.class, args);
}
}
/**
* 服务提供者方法
* @author zhouzhaodong
*/
@RestController
@RequestMapping("/order")
public class OrderController {
/**
* 测试方法
* @return
*/
@RequestMapping("/getMessage")
public String getMessage(){
return "order-one";
}
}
这里我们发现注册中心上面多了一个服务。
显示内容如下:
至此服务提供者创建完毕!
构建方式和上面一样,就不再赘述了。
#eureka-client
#端口号
server:
port: 8083
eureka:
instance:
hostname: localhost
#置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址,默认是http://localhost:8761/eureka;多个地址可用,分隔
client:
service-url:
default-zone: http://localhost:8761/eureka/
spring:
application:
name: service-user
/**
* 服务消费者
* @author zhouzhaodong
*/
@EnableEurekaClient
@SpringBootApplication
public class ServerUserApplication {
/**
* @Bean 注解用来注入restTemplate
* @LoadBalanced 注解用来在注册中心里进行查找微服务,Ribbon负载均衡
* 生成一个RestTemplate实例对象
* 使用user服务调用order服务就是通过这个restTemplate对象实现的
* @return
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ServerUserApplication.class, args);
}
}
/**
* 消费者
*
* @author zhouzhaodong
*/
@RestController
public class UserController {
@Resource
private RestTemplate restTemplate;
/**
* 返回值类型需要和我们的业务返回值一致
* @return
*/
@RequestMapping("getUserOrder")
public String getUserOrder() {
String url = "http://service-order/order/getMessage";
return restTemplate.getForObject(url, String.class);
}
}
发现注册中心页面多了一个服务
可以发现成功调用了order服务并返回了结果,实现了server-user服务调用server-order服务的操作。服务消费者本身又是服务提供者。
至此消费者搭建完毕!
https://github.com/zhouzhaodo...
http://www.zhouzhaodong.xyz