parent
b04943736a
commit
05dcaedfae
@ -0,0 +1,49 @@
|
|||||||
|
package com.dsideal.gw.Index.Controller;
|
||||||
|
import com.jfinal.core.Controller;
|
||||||
|
import okhttp3.OkHttpClient;
|
||||||
|
import okhttp3.Request;
|
||||||
|
import okhttp3.Response;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class ApiController extends Controller {
|
||||||
|
|
||||||
|
private OkHttpClient client = new OkHttpClient();
|
||||||
|
|
||||||
|
public void index() {
|
||||||
|
String path = getPara(); // 获取请求路径
|
||||||
|
String serviceUrl = route(path); // 根据路径决定转发到哪个微服务
|
||||||
|
|
||||||
|
if (serviceUrl == null) {
|
||||||
|
renderJson("error", "Service not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Request request = new Request.Builder()
|
||||||
|
.url(serviceUrl)
|
||||||
|
.header("Authorization", getHeader("Authorization"))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
Response response = client.newCall(request).execute();
|
||||||
|
if (response.isSuccessful()) {
|
||||||
|
renderJson(response.body().string());
|
||||||
|
} else {
|
||||||
|
renderJson("error", "Service request failed");
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
renderJson("error", "Exception occurred: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String route(String path) {
|
||||||
|
// 根据路径决定转发到哪个微服务
|
||||||
|
// 这里可以根据具体的路径或者配置文件来路由
|
||||||
|
if (path.startsWith("/service1")) {
|
||||||
|
return "http://localhost:8081" + path; // 微服务1的地址
|
||||||
|
} else if (path.startsWith("/service2")) {
|
||||||
|
return "http://localhost:8082" + path; // 微服务2的地址
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.dsideal.gw.Interceptor;
|
||||||
|
|
||||||
|
import com.jfinal.aop.Interceptor;
|
||||||
|
import com.jfinal.aop.Invocation;
|
||||||
|
import com.jfinal.core.Controller;
|
||||||
|
|
||||||
|
public class AuthInterceptor implements Interceptor {
|
||||||
|
@Override
|
||||||
|
public void intercept(Invocation inv) {
|
||||||
|
Controller controller = inv.getController();
|
||||||
|
String token = controller.getHeader("Authorization");
|
||||||
|
|
||||||
|
// 这里添加你的鉴权逻辑,例如检查 token 是否有效
|
||||||
|
if (!isValidToken(token)) {
|
||||||
|
controller.renderJson("error", "Unauthorized");
|
||||||
|
} else {
|
||||||
|
inv.invoke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isValidToken(String token) {
|
||||||
|
// 添加你的 token 验证逻辑
|
||||||
|
return "valid-token".equals(token);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue