首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

Ratpack:构建简单高效的 HTTP 微服务-2

Ratpack:构建简单高效的 HTTP 微服务-2

HTTP 头Request 和 Response 接口都提供了 getHeaders 方法来获取到 HTTP 头,不过 Request 接口的 getHeaders 方法返回的是不可变的 Headers 接口对象,而 Response 接口的 getHeaders 方法返回的是可变的 MutableHeaders 接口对象。Headers 接口中的 get 和 getAll 方法可以根据名称获取 HTTP 头的值。MutableHeaders 接口提供了 add、set 和 remove 方法来对 HTTP 头进行修改。
中获取了 HTTP 请求中 X-UID 头的内容,并作为 HTTP 响应的内容发送回来。
清单 5. HTTP 头处理
1
2
3
4
5
6
7
8
9
RatpackServer.start(server ->
server.handlers(chain ->
chain.get(ctx -> {
  String userId = ctx.getRequest().getHeaders().get("X-UID");
  ctx.getResponse().getHeaders().set("X-Poweredby", "Ratpack");
  ctx.render(userId);
})
)
);




CookieCookie 也是 HTTP 处理中的重要部分。Request 接口中的 getCookies 方法可以获取到全部 Cookie 的集合,oneCookie 方法可以根据名称获取某个 Cookie 的值。Response 接口的 cookie 方法用来创建一个 Cookie。
中使用 Request 接口的 oneCookie 方法来读取 Cookie 的值,使用 Response 接口的 cookie 方法来设置 Cookie 的值。
清单 6. Cookie 处理
1
2
3
4
5
6
7
8
9
RatpackServer.start(server ->
server.handlers(chain ->
chain.get(ctx -> {
  String userId = ctx.getRequest().oneCookie("userId");
  ctx.getResponse().cookie("userId", "value");
  ctx.render(userId);
})
)
);




Spring 集成Ratpack 提供了与 Spring 框架的集成。集成的方式有两种。第一种是在 Ratpack 应用中使用 Spring 框架提供的依赖注入功能。之前介绍过 Ratpack 中的 Registry 接口提供了对象的注册和查找功能。这个功能可以用 Spring 来替代,也就是由 Spring 来负责 Registry 中对象的创建和管理。这样就可以充分利用 Spring 强大的依赖注入功能来简化 Ratpack 应用的开发。
在 中,Greeting 是一个作为示例的接口。AppConfiguration 是 Spring 框架使用的配置类,在其中定义了一个 Greeting 接口的实现对象。在启动 Ratpack 服务器时,通过 registry 方法来指定一个 Registry 接口的实现,而 ratpack.spring.Spring.spring 方法则把一个 Spring 的配置类转换成 Registry 对象。这样在处理器的实现中就可以从 Context 中查找到 Greeting 接口的实现对象并使用。
清单 7. 在 Ratpack 中使用 Spring 的依赖注入功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
RatpackServer.start(server -> server
.registry(spring(AppConfiguration.class))
.handlers(chain -> chain
.get(ctx -> ctx
  .render(ctx.get(Greeting.class).say("Alex")))
)
);

public interface Greeting {
String say(final String name);
}

@Configuration
class AppConfiguration {
@Bean
public Greeting greeting() {
return name -> String.format("Hello, %s", name);
}
}




另外一种与 Spring 集成的方式是在 Spring Boot 中把 Ratpack 作为 Servlet 容器的替代。在 中,在 Spring Boot 启动类中添加注解 @EnableRatpack 来启用 Ratpack。Ratpack 中处理器的逻辑定义在 Action<Chain>类型的对象中。这与代码清单中启动 Ratpack 服务器时使用的 handlers 方法的作用是相同的。
清单 8. 在 Spring Boot 中使用 Ratpack
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@SpringBootApplication
@EnableRatpack
public class SpringBootApp {
@Bean
public Action<Chain> index() {
return chain -> chain
  .get(ctx -> ctx
    .render(greeting().say("Alex"))
  );
}

public Greeting greeting() {
return name -> String.format("Hello, %s", name);
}

public static void main(String... args) throws Exception {
SpringApplication.run(SpringBootApp.class, args);
}
}

返回列表