springCloud微服务入门

前言

springCloud是一个微服务框架集。
eureka来实现zookeeper;

Eureka

注册中心server

新建

选择版本: 1.5.17
cloud dicovery ---  eureka server

配置

  • 启动类
# 启动类添加注解:
@EnableEurekaServer
  • 简单配置
# application.yml
server:
  port: 8761
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka/

查看127.0.0.1:8761/

  • 集群配置
# application.yml
spring:
  application:
    name: server中心
  profiles:
    active: server1

# application-server1.yml
server:
  port: 8761
eureka:
  instance:
    hostname: server1
  client:
    service-url:
      defaultZone: http://127.0.0.1:8762/eureka/ # 后面可以添加更多地址,用逗号分隔

# application-server2.yml
server:
  port: 8762
eureka:
  instance:
    hostname: server2
  client:
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka/

启动参数

--spring.profiles.active=prod

服务提供者service

新建

和注册中心一样

配置

  • 启动类
和注册中心一样
  • 简单配置
spring:
  application:
    name: service01
server:
  port: 8081

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

服务消费者controller

新建

和之前一样

配置

  • 启动类
# 添加注解
@EnableDiscoveryClient

# 添加属性
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
    return new RestTemplate();
}
  • 配置
spring:
  application:
    name: controller01
server:
  port: 8764
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/ 

使用

@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("test")
    public String test() {
        String forObject = restTemplate.getForObject("http://service01/test", String.class);
        return forObject;
    }
}

Feign负载均衡

  • 引用
<dependency>
   	<groupId>org.springframework.cloud</groupId>
  	<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
  • 启动类
@EnableFeignClients
@EnableDiscoveryClient
  • service层接口
@FeignClient(value = "springcloud-server")
public interface TestService {
 
   @RequestMapping("/test")
   public String test();
 
}
  • controller调用
@RestController
public class TestController {
 
   @Autowired
   private  TestService testService;
 
   @RequestMapping(value = "/test",method = RequestMethod.GET)
   public String test(){
      return  testService.test();
   }
}
posted @ 2018-11-24 19:36  田云  阅读(306)  评论(0编辑  收藏  举报