可以通过以下步骤实现:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webclient</artifactId>
</dependency>
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
@Service
public class GithubService {
private final WebClient webClient;
public GithubService() {
this.webClient = WebClient.create();
}
public Mono<Repository> getRepository(String owner, String repoName) {
String apiUrl = String.format("https://api.github.com/repos/%s/%s", owner, repoName);
return webClient.get()
.uri(apiUrl)
.retrieve()
.bodyToMono(Repository.class);
}
}
public class Repository {
private String name;
private String description;
private int stargazers_count;
// Getters and setters
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class RepositoryController {
private final GithubService githubService;
@Autowired
public RepositoryController(GithubService githubService) {
this.githubService = githubService;
}
@GetMapping("/repositories/{owner}/{repoName}")
public Mono<Repository> getRepository(@PathVariable String owner, @PathVariable String repoName) {
return githubService.getRepository(owner, repoName);
}
}
http://localhost:8080/repositories/{owner}/{repoName}
其中,{owner}和{repoName}分别替换为Github存储库的所有者和存储库名称。
这样,就可以通过Spring从Github API获取星形存储库的信息了。根据具体需求,可以进一步处理响应数据,例如展示存储库的名称、描述和星标数等。
领取专属 10元无门槛券
手把手带您无忧上云