项目中有时会需要将一些功能暴露为webservice接口供其他应用调用,restful作为轻量级webservice是为不错的选择,使用resteasy我们需要很少的代码编写即可实现。
废话少说,上代码
示例model
public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;
@Path("/user")
public interface UserService {
String MEDIA_TYPE_JSON_UTF8 = MediaType.APPLICATION_JSON + ";charset=UTF-8";
@GET
@Path("/{id}")
@Produces(MEDIA_TYPE_JSON_UTF8)
User get(@PathParam("id") String id);
@GET
@Path("/all")
@Produces(MEDIA_TYPE_JSON_UTF8)
List all();
@POST
@Path("/add")
@Produces(MEDIA_TYPE_JSON_UTF8)
@Consumes(MEDIA_TYPE_JSON_UTF8)
User add(User user);
@DELETE
@Path("/{id}")
@Produces(MEDIA_TYPE_JSON_UTF8)
void delete(@PathParam("id") String id);
}
webservice接口实现(省略Dao实现)
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Service("DefaultUserService")
@Transactional
public class DefaultUserService implements UserService {
@Resource
private UserDao userDao;
@Override
public User get(String id) {
return userDao.get(id);
}
@Override
public List all() {
return userDao.queryAll();
}
@Override
public User add(User user) {
return userDao.save(user);
}
@Override
public void delete(String id) {
userDao.delete(id);
}
}
rest服务端(jetty内嵌实现)
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap;
import org.jboss.resteasy.plugins.spring.SpringContextLoaderListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
@Component("restServer")
public class RestServer {
private Logger logger = LoggerFactory.getLogger(getClass());
private Server restServer;
private String hostIp = "127.0.0.1";
private int port = 8097;
@PostConstruct
public void init(){
restServer = new Server();
final List connectors = new ArrayList<>();
ServerConnector connectorV4 = new ServerConnector(restServer);
connectorV4.setHost(hostIp);
connectorV4.setPort(port);
connectors.add(connectorV4);
logger.info("IPV4 Connector Info:HostIP:"+this.hostIp+", Port:"+this.port);
restServer.setConnectors(connectors.toArray(new Connector[connectors.size()]));
ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setContextPath("/");//设置上下文
contextHandler.addEventListener(new ResteasyBootstrap());
contextHandler.addEventListener(new SpringContextLoaderListener());//instead of ContextLoaderListener
contextHandler.setInitParameter("contextConfigLocation", "classpath:spring.xml");
ServletHolder holder = new ServletHolder(HttpServletDispatcher.class);
holder.setInitParameter("resteasy.servlet.mapping.prefix", "/");//resteasy前缀
holder.setInitOrder(1);
holder.setAsyncSupported(true);
contextHandler.addServlet(holder,"/*");//servlet过滤规则
restServer.setHandler(contextHandler);
try {
restServer.start();
} catch (Exception e) {
logger.error("rest server start failed!");
logger.error(e.getMessage(), e);
}
}
@PreDestroy
public void destroy() {
if(restServer != null){
try {
restServer.stop();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
public void setHostIp(String hostIp) {
this.hostIp = hostIp;
}
public void setPort(int port) {
this.port = port;
}
public static void main(String[] args) {
RestServer resourcePackageRest = new RestServer();
resourcePackageRest.init();
System.out.println("rest server started successful!");
}
}
maven 依赖
org.jboss.resteasy
jaxrs-api
3.0.11.Final
org.jboss.resteasy
resteasy-jaxrs
3.0.11.Final
org.jboss.resteasy
resteasy-jackson2-provider
3.0.11.Final
org.jboss.resteasy
resteasy-servlet-initializer
3.0.11.Final
org.jboss.resteasy
resteasy-spring
3.0.11.Final
org.springframework
spring-core
4.1.5.RELEASE
org.springframework
spring-context
4.1.5.RELEASE
org.springframework
spring-web
4.1.5.RELEASE
org.eclipse.jetty
jetty-server
9.4.6.v20170531
org.eclipse.jetty
jetty-servlet
9.4.6.v20170531
此时,restful服务端已成功部署,浏览器可访问测试,resteasy会根据注解自动部署为webservice
restful客户端代码,非常简单的代码,通过ResteasyClient的target方法,会生成ResteasyWebTarget对象,通过他的proxy可直接生成对应api接口的rest客户端
import user.apis.UserService;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
public class RestResourcePackageClient{
private ResteasyWebTarget baseTarget;
private String baseUri;
public void init(){
if(baseUri == null || baseUri.length()==0){
throw new NullPointerException("base uri is null!");
}
ResteasyClient client = new ResteasyClientBuilder().build();
baseTarget = client.target(baseUri);
}
public UserService userService() {
return baseTarget.proxy(UserService.class);
}
public void setBaseUri(String baseUri) {
this.baseUri = baseUri;
}
}
客户端pom依赖
user.respack
respack-api
${project.version}
org.jboss.resteasy
resteasy-client
3.0.11.Final
org.jboss.resteasy
resteasy-jackson2-provider
3.0.11.Final
com.fasterxml.jackson.core
jackson-annotations
2.9.0.pr4
测试client
public class LocalTest {
public static void main(String[] args) throws BusinessException {
RestResourcePackageClient restResourcePackageClient = new RestResourcePackageClient();
restResourcePackageClient.setBaseUri("http://127.0.0.1:8097/");
restResourcePackageClient.init();
UserService userService = restResourcePackageClient.userService();
userService.all().forEach((user -> System.out.println("id:"+user.getId()+",name:"+user.getName())));
}
}