如何解决Spring boot:如何访问rest控制器中的服务对象
我正在尝试创建一个将执行两个任务的 Spring Boot 应用程序:
- 运行一个线程,该线程将定期查询 mongo 数据库中的活动用户数(使用每个用户文档中的最后一个 ping 时间戳字段来确定状态)
- 提供一个rest api,它提供由上述确定的最新活跃用户数
第 1 部分的服务代码如下,每 5 秒更新一次计数:
@Service
public class Service implements CommandLineRunner {
@Autowired
private UserRepository repository;
@Getter private int tMinus = 20;
@Getter private int refreshFreq = 5;
public long activeUserCount;
public static void main(String[] args) {
SpringApplication.run(Service.class,args);
}
@Override
public void run(String... args) throws Exception {
while(true) {
try {
//Get last ping cutoff to determine active users
Double minLastPingTime = (System.currentTimeMillis()) - (Double.valueOf(getTMinus()*1000));
//Update the activeUserCount property with the latest number of active users
activeUserCount = (repository.countByLastPingTimeGreaterThan(minLastPingTime));
System.out.println("Active User count: "+ activeUserCount);
// Wait for the configured number of seconds
Thread.sleep(getRefreshFreq()*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Bean
public long getActiveUserCount(){
return activeUserCount;
}
}
以及第 2 部分的其余控制器:
@RestController
class ActiveUserCountController {
@Autowired
private long getActiveUserCount;
@GetMapping("/getActiveUserCount")
public long activeUserCount() {
return getActiveUserCount;
}
}
第 1 部分工作正常 - db 查询正确执行,并将正确数量的活动用户打印到日志中,例如:
活跃用户数:100
第 2 部分不起作用 - 如果我尝试访问 http://localhost:8080/getActiveUserCount,返回的计数为 0。要启动应用程序,必须将 Service 中的 getActiveUserCount() 方法配置为 Bean,但是当它自动连接到 rest 控制器时,它会初始化为一个具有默认值的字段,而不是调用定义的方法。
这是正确的方法,还是有更好的方法从控制器内部访问服务对象?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。