Eureka的注册与发现,简单使用

对比dubbo,Eureka也应该有:注册中心,提供者,调用者,监控中心
第一步配置注册中心:
① 依赖service:

 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

② 配置文件yml文件:

server:
  port: 8761
spring:
  application:
    name: SCW-REGISTER
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false #此EurekaServer不在注册到其他的注册中心
    fetch-registry: false       #不在从其他中心中心拉取服务器信息
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka

③ 主启动类,开启注解。

@SpringBootApplication
@EnableEurekaServer
public class ScwRegisterApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScwRegisterApplication.class);
    }
}

第二步:配置提供者(除了注册中心service,提供,调用均为client)
① 引入依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

②配置文件yml:(我这里还配置了数据库,redis,日志)

#端口
server:
  port: 8000
#redis
spring:
  redis:
    host: 192.168.188.128
    port: 6379
#数据库 
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/atcrowdfunding_0155?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    filters: stat  #开启监控过滤器
#名称
  application:
    name: SCW-PROJECT
#mybatis
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:com/offcn/user/mapper/*.xml
#eureka配置
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
#日志
logging:
  file:
    path: e:\\log\\scw-project
  level:
    com:
      offcn: debug

第三步:主启动项:开启注解

@SpringBootApplication
@EnableDiscoveryClient //范围更大的 服务提供者可以为zookeeper
@MapperScan("com.offcn.project.mapper")
public class ScwProjectStart {

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

第三步:Ribbon配置调用者(调用者比提供者多配置两项:声明RESTTemplate和远程调用)
① 引入依赖

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

② 配置文件yml:

server:
  port: 7000
spring:
  redis:
    host: 192.168.188.128
    port: 6379
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/atcrowdfunding_0155?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    filters: stat  #开启监控过滤器
  application:
    name: SCW-USER
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:com/offcn/user/mapper/*.xml
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

logging:
  file:
    path: e:\\log\\scw-user
  level:
    com:
      offcn: debug

③声明RESTTemplate,主启动类开启注解

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker   //开启熔断机制
public class ConsumerUserStart {

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

    @LoadBalanced   //开启负载均衡  //默认的负载均衡策略 轮询
    @Bean    //<bean id="" class="">
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

④ 远程服务调用
接口:

public interface UserService {

    public User getUserById(Long id);
   
    public Map<String,Object> buyMovie(Long userId);
}

实现

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RestTemplate restTemplate;
@Override
    @HystrixCommand(fallbackMethod = "buyMovieFallbackMethod")
    public Map<String, Object> buyMovie(Long userId) {
        Map<String, Object> resultMap = new HashMap<>();
        //1.根据userId查询用户对象
        User user = this.getUserById(userId);
        //2.远程调用电影服务接口查询电影对象
        Movie movie = restTemplate.getForObject("http://EUREKAPROVIDE/movie/getNewMovie", Movie.class);
        System.out.println(movie);
        //3.设置map
        resultMap.put("user", user);
        resultMap.put("movie", movie);
        return resultMap;
    }
//触发熔断后做降级处理的方法 ,原则,参数和放回类型要与原方法保持一致
    public Map<String, Object> buyMovieFallbackMethod(Long userId) {
        Map<String, Object> resultMap = new HashMap<>();
        User user = new User(-1L,"查无此用户");
        Movie movie = new Movie(-1L,"该电影还没有上映");
        resultMap.put("user",user);
        resultMap.put("movie",movie);
        return resultMap;
    }
 }

controller

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUserById")
    public User getUserById(Long id){
        return userService.getUserById(id);
    }
    @RequestMapping("/buyMovie")
    public Map buyMovie(Long userId){
        return userService.buyMovie(userId);
    }

========================================
feign
①依赖

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--熔断-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!--监控请求-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--熔断监控-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>

②yml配置文件

server:
  port: 6666
spring:
  application:
    name: CustomFegin #服务名称
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
  instance:
    prefer-ip-address: true

③主启动类

@SpringBootApplication
@EnableDiscoveryClient    //相比 @EnableEurekaClient 范围大    注册中心可以是其它组件
@EnableFeignClients       //开启feign
//@EnableCircuitBreaker //开启熔断机制
//@EnableHystrixDashboard //开启熔断监控
public class ConsumerFeignUserStart {

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

}

④fegin需要多写一个接口,一个实现
fegin的接口

@FeignClient(value = "EUREKAPROVIDE")    //远程调用的服务ID
public interface MovieServiceFeign {

    @GetMapping("/movie")   //服务提供者提供服务
    public Movie getNewMovie();
}

实现

@Component
public class MovieServiceExceptionFeign implements MovieServiceFeign {
    @Override
    public Movie getNewMovie() {
        Movie movie =  new Movie(-1L,"该电影还没有上映");
        return movie;
    }
}

user接口,测试接口

public interface UserService {

    public User getUserById(Long id);


    public Map<String,Object> buyMovie(Long userId);
}

user测试接口的,实现

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private MovieServiceFeign movieServiceFeign;


    @Override
    public User getUserById(Long id) {
        return userDao.getUserById(id);
    }

    @Override
    public Map<String, Object> buyMovie(Long userId) {
        Map<String, Object> resultMap = new HashMap<>();
        //1.根据userId查询用户对象
        User user = this.getUserById(userId);
        //2.远程调用电影服务接口查询电影对象
        Movie movie = movieServiceFeign.getNewMovie();
        //3.设置map
        resultMap.put("user", user);
        resultMap.put("movie", movie);
        return resultMap;
    }
}

controller

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUserById")
    public User getUserById(Long id){
        return userService.getUserById(id);
    }


    @RequestMapping("/buyMovie")
    public Map buyMovie(Long userId){
        return userService.buyMovie(userId);
    }
}

fegin对比ribbon:
fegin需要多写一个接口一个实现,ribbon需要引入模板,重写方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值