SpringCloud学习第四篇:Feign学习(Hoxton.SR4)

一、Feign是什么?

Feign是一个声明式WebService客户端。使用Feign能让编写Web Service客户端更加简单,它的使用方法就是定义一个接口,然后在上面添加注解,同时也支持JAX-RS标准的注解。Feign也支持可插拔式的编码器和解码器。SpringCloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters,并整合了Ribbon和Eureka,从而让Feign的使用更加方便。在Spring Cloud feign的实现下,只需要创建一个接口并用注解方式配置它,即可完成服务提供方的接口绑定,简化了在使用Spring Cloud Ribbon时自行封装服务调用客户端的开发量。

二、工程的搭建

2.1、公共接口(spring-cloud-interface-demo)

  • Maven
   <dependencies>
        <!-- 服务调用 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>
  • dto
@Data
public class UserDto {

    /**
     * ID
     */
    private Long id;

    /**
     * 用户名称
     */
    private String name;

}
  • 接口
@FeignClient(name="service-demo")
public interface UserService {
    /**
     * 保存用户
     * @param user
     */
    @PostMapping("/user/save")
    boolean saveUser( UserDto user);
    /**
     * 查询所有的用户列表
     */
    @GetMapping("/user/find/all")
    List<UserDto> findAll();
}

2.3、服务提供者(spring-cloud-service-demo)

  • Maven
    <dependencies>
    <!-- 依赖 API -->
    <dependency>
        <groupId>com.yk</groupId>
        <artifactId>spring-cloud-interface-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <!-- 依赖 Spring Cloud eureka client -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
   </dependencies>
  • application.properties
# Tomcat
server:
  port: 1201
spring:
  application:
    name: service-demo
eureka:
  client:
    service-url:
      #注册地址
      defaultZone: http://localhost:1101/eureka/
  #显示服务器IP加端口
  instance:
    hostname: localhost
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
  • 启动入口类
@SpringBootApplication
@EnableDiscoveryClient //eureka
public class ServiceDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceDemoApplication.class, args);
    }
}
  • service
public interface UserService {
    /**
     * 保存用户
     * @param user
     */

    boolean saveUser( UserDto user);
    /**
     * 查询所有的用户列表
     */

    List<UserDto> findAll();
}
@Service
public class  UserServiceImpl implements UserService {

    private Map<Long, UserDto> repository = new ConcurrentHashMap<>();

    @Override
    public boolean saveUser(UserDto user) {
        return repository.put(user.getId(), user) == null;
    }

    @Override
    public List<UserDto> findAll() {
        return new ArrayList(repository.values());
    }
}
  • Controller
@RestController
@RequestMapping("user")
public class DemoController {
    @Autowired
    private UserService userService;

    @PostMapping("save")
    public boolean saveUser(@RequestBody UserDto user) {
        return userService.saveUser(user);
    }

    @GetMapping("find/all")
    public List<UserDto> findAll() {
        return userService.findAll();
    }
}

2.4、服务调用者(spring-cloud-web-demo)

  • Maven
    <dependency>
        <groupId>com.yk</groupId>
        <artifactId>spring-cloud-interface-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
  • application.properties
spring.application.name = spring-cloud-api-client
## 服务端口
# Tomcat
server:
  port: 1301
spring:
  application:
    name: web-demo
eureka:
  client:
    service-url:
      #注册地址
      #      defaultZone: http://localhost:1101/eureka/,http://localhost:11010/eureka/
      defaultZone: http://localhost:1101/eureka/
  #显示服务器IP加端口
  instance:
    hostname: localhost
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port}

  • 启动入口类
@SpringBootApplication
//声明 UserService接口作为Feign Client 调用
@EnableFeignClients(clients = UserService.class)
@EnableDiscoveryClient
public class WebDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebDemoApplication.class, args);
    }
}
  • Service
public class DemoService {
    /**
     * 保存用户
     * @param user
     */

    boolean saveUser( UserDto user);
    /**
     * 查询所有的用户列表
     */

    List<UserDto> findAll();
}
  • ServiceImpl
@RestController
public class DemoServiceImpl implements DemoService {
    @Autowired
    private UserService userService;
    @Override
    public boolean saveUser(UserDto user) {
        return userService.saveUser(user);
    }
    @Override
    public List<UserDto> findAll() {
        return userService.findAll();
    }
}
  • Controller
@RestController
@RequestMapping("damo")
public class DemoController {
    @Autowired
    private DemoService demoService;
    @PostMapping("save")
    public boolean saveUser(@RequestBody UserDto user) {
        return demoService.saveUser(user);
    }
    @GetMapping("queryAll")
    public List<UserDto> findAll() {
        return demoService.findAll();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java.lang.IllegalStateException: Failed to execute CommandLineRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at com.unkown.data.hw.ipran.straight.collect.UnkownDataHwIpranStraightCollectApplication.main(UnkownDataHwIpranStraightCollectApplication.java:39) [classes/:na] Caused by: feign.FeignException$InternalServerError: [500 INTERNAL SERVER ERROR] during [POST] to [http://ants-flask/api/collect/endpoint] [RemoteIpranScanService#endpoint(String)]: [<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>TypeError: unsupported operand type(s) for +: 'int' and 'str' // Wer... (20567 bytes)] at feign.FeignException.serverErrorStatus(FeignException.java:231) ~[feign-core-10.10.1.jar:na] at feign.FeignException.errorStatus(FeignException.java:180) ~[feign-core-10.10.1.jar:na] at feign.FeignException.errorStatus(FeignException.java:169) ~[feign-core-10.10.1.jar:na] at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:92) ~[feign-core-10.10.1.jar:na] at feign.AsyncResponseHandler.handleResponse(AsyncResponseHandler.java:96) ~[feign-core-10.10.1.jar:na] at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:138) ~[feign-core-10.10.1.jar:na] at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:89) ~[feign-core-10.10.1.jar:na] at com.alibaba.cloud.sentinel.feign.SentinelInvocationHandler.invoke(SentinelInvocationHandler.java:107) ~[spring-cloud-starter-alibaba-sentinel-2.2.3.RELEASE.jar:2.2.3.RELEASE] at com.sun.proxy.$Proxy131.endpoint(Unknown Source) ~[na:na] at com.unkown.data.hw.ipran.straight.collect.controller.RTrsHwIpranCircuitController.IpranSend(RTrsHwIpranCircuitController.java:94) ~[classes/:na] at com.unkown.data.hw.ipran.straight.collect.MyRunner.run(MyRunner.java:22) ~[classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] ... 5 common frames omitted
06-06

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值