Http服务化改造实践(三)

WilliamGates
发布于 2022-6-21 16:16
浏览
0收藏

 

4.2 服务端实现公共API
首先需要添加相应的maven依赖,代码如下:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.vhicool</groupId>
            <artifactId>feign-api</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>

 

服务端采用继承方式实现,具体代码如下所示:

@Controller
@RequestMapping
public class UserController implements IUserController {
 @Override
 @ResponseBody
 public List<String> listAll(String name) {
  ArrayList<String> list = new ArrayList<>();
  list.add("达菲");
  list.add("olu");
  list.add(name);
  return list;
 }
}

 

4.3 客户端实现公共API
客户端首先同样需要增加相应的依赖,具体代码如下所示:

         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
         <dependency>
            <groupId>com.vhicool</groupId>
            <artifactId>feign-api</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>

 

客户端服务调用类需要继承公共API:

@FeignClient(value = "user", url = "http://localhost:8080")
public interface UserApi extends IUserController {
}

同时客户端启动类需要增加@EnableFeignClients注解,具体示例代码如下所示:

@SpringBootApplication
@EnableFeignClients
public class ManagerApplication {
 public static void main(String[] args) {
  SpringApplication.run(ManagerApplication.class, args);
 }
}

同样基于Springboot编程方式,可以为Feign配置全局参数,具体如下:

@Configuration
public class FeignConfiguration {
 /**
  * 请求超时时间
  * @return
  */
 @Bean
 public Request.Options options() {
  return new Request.Options(2000, 3500);
 }
  //拦截器等定义
}

接下来客户端就可以用如下方式进行调用:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
 @Autowired
 private UserApi userApi;

 @Test
 public void listAll() {
  System.out.println(userApi.listAll("饼饼"));
 }
}

时,当前项目编译的jar包,类也已经被替换成我们自定义的类,目标达成。

 

文章转自公众号:中间件兴趣圈

标签
已于2022-6-21 16:16:37修改
收藏
回复
举报
回复
    相关推荐