我正在使用Kohsuke GitHub-API从我的 Java(服务器端)应用程序连接到 GitHub,并且我想使用OkHttp缓存来自 GitHub 的响应的能力。当我为它编写测试时,这非常有效,但它在应用程序本身中不起作用,我不知道为什么会这样。我设法将问题追溯到创建 URLConnection 对象时,该对象的 useCache 变量设置为 false,但我不知道为什么。它可能与服务器配置或类似的东西有关吗?
我将不胜感激任何想法,甚至向任何方向轻推,因为坦率地说,我没有任何想法......谢谢
提供者:
public class GitHubProvider implements Provider<GitHub> {
@Override
public GitHub get() {
GitHub gitHub = null;
HttpResponseCache cache = null;
OkHttpClient okHttpClient = new OkHttpClient();
File cacheDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
try {
cache = new HttpResponseCache(cacheDir, 10L * 1024 * 1024);
} catch (IOException e) {
// NOTHING
}
okHttpClient.setResponseCache(cache);
try {
gitHub = GitHub.connectUsingPassword("user", "password");
} catch (Exception e) {
// NOTHING
}
gitHub.setConnector(new OkHttpConnector(okHttpClient));
return gitHub;
}
}
测试(作品):
@RunWith(JukitoRunner.class)
public class SoftwareComponentServiceTest {
public static class Module extends TestModule {
@Override
protected void configureTest() {
bind(GitHub.class).toProvider(GitHubProvider.class);
}
}
@Inject
GitHub gitHub;
@Test
public void testInjectedGitHubResponseCache() {
try {
GHUser ghUser = gitHub.getUser("user");
GHRepository repository = ghUser.getRepository("repository");
int limit = gitHub.getRateLimit().remaining;
repository.getFileContent("README.md");
assertEquals(limit - 1, gitHub.getRateLimit().remaining);
repository.getFileContent("README.md");
assertEquals(limit - 1, gitHub.getRateLimit().remaining);
} catch (IOException e) {
e.printStackTrace();
}
}
}
应用程序中使用的服务(不起作用):
@Singleton
@RequiresAuthentication
public class SoftwareComponentService {
@Inject
GitHub gitHub;
public List<SoftwareComponent> findAll() {
List<SoftwareComponent> softwareComponentList = new ArrayList<SoftwareComponent>();
try {
GHUser ghUser = gitHub.getUser("user");
List<GHRepository> repositories = ghUser.listRepositories().asList();
for (int i = 0; i < repositories.size(); i++) {
GHRepository repository = repositories.get(i);
if (!repository.getName().startsWith("sc_")) {
continue;
}
softwareComponentList.add(new SoftwareComponent(repository.getName(), repository.getDescription()));
}
} catch (IOException e) {
// NOTHING
}
return softwareComponentList;
}
}