How to run spring boot admin client and server in same application - spring

I want to run a spring boot admin server and client inside the same application.I changed server port, when I change the server port spring admin will access my changed port. so I can run an admin server. but I can't see my web application pages.
i need output like this.
Localhost:8080/myapplication (my client application)
localhost:8090/admin (spring boot admin server)

Here is a simple example to run the application on two different ports for admin client and for server client.
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplicationBuilder parentBuilder = new SpringApplicationBuilder(Application.class);
parentBuilder.child(ServiceOneConfiguration.class).properties("server.port:8081").run(args);
parentBuilder.child(ServiceTwoConfiguration.class).properties("server.port:8082").run(args);
}
#Service
static class SharedService {
public String getMessage(String name) {
return String.format("Hello, %s, I'm shared service", name);
}
}
#Configuration
#EnableAutoConfiguration
static class ServiceOneConfiguration {
#Controller
#RequestMapping("/server")
static class ControllerOne {
#Autowired
private SharedService service;
#RequestMapping(produces = "text/plain;charset=utf-8")
#ResponseBody
public String getMessage(String name) {
return "ControllerOne says \"" + service.getMessage(name) + "\"";
}
}
}
#Configuration
#EnableAutoConfiguration
static class ServiceTwoConfiguration {
#Bean
EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.setUriEncoding("cp1251");
return tomcat;
}
#Controller
#RequestMapping("/client")
static class ControllerTwo {
#Autowired
private SharedService service;
#RequestMapping(produces = "text/plain;charset=utf-8")
#ResponseBody
public String getMessage(String name) {
return "ControllerTwo says \"" + service.getMessage(name) + "\"";
}
}
}
}
For more detail here is a link:
spring-boot-connectors
Hope this will help.

we can use spring boot multi modules like following.
main app
spring-boot-admin
pom.xml ( running port 8888 )
my project
pom.xml ( running port 8080 )
pom.xml

Related

Spring boot controller not being detected

Good day. I'm having issues with my Springboot app. The controller isn't being detected.The Component scan is used but it won't detect the controllers.
Folder structure
Application
#EntityScan(basePackages = "com.jokedata.models")
#EnableJpaRepositories(basePackages = "com.jokedata.repositories")
//#ComponentScan(basePackages = {"com.jokeweb.project.controllers"})
#SpringBootApplication(scanBasePackages = "com.jokeweb.project.controllers")
public class JokeApplication {
public static void main(String[] args) {
SpringApplication.run(JokeDataApplication.class, args);
}
}
Controller
#RestController
public class UserController {
#GetMapping("/home")
public String home() {
return "home";
}
}
Check if request URL or application port is correct or not.

Spring get open websocket connections

I am using Spring Boot Websocket to enable my Spring Boot 2 microservice to deal with websocket connections.
My config:
#Configuration
#EnableWebSocket
public class WsConfig implements WebSocketConfigurer {
#Autowired
WebSocketHandler webSocketHandler;
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
DefaultHandshakeHandler handshakeHandler = new DefaultHandshakeHandler();
handshakeHandler.setSupportedProtocols(HANDSHAKE_PROTOCOL);
registry.addHandler(webSocketHandler, WS_HANDLER_PATH + WILDCARD)
.setAllowedOrigins("*")
.setHandshakeHandler(handshakeHandler);
}
}
My clients are able to connect to my Service via Websocket. I am implementing WebSocketHandler interface to handle messages and log connections.
Now my question: Is there a way to show all current websocket users/sessions?
I was trying to use the SimpUserRegistry:
#Configuration
public class UserConfig {
final private SimpUserRegistry userRegistry = new DefaultSimpUserRegistry();
#Bean
public SimpUserRegistry userRegistry() {
return userRegistry;
}
}
and to show the users via a REST endpoint
#RestController
public class WebSocketManager {
private final SimpUserRegistry userRegistry;
public WebSocketManager(SimpUserRegistry userRegistry) {
this.userRegistry = userRegistry;
}
#GetMapping(path = "/users")
public List<String> getConnectedUsers() {
userRegistry.getUsers().stream()
.map(SimpUser::getName)
.forEach(System.out::println);
System.out.println("Users " + userRegistry.getUsers());
System.out.println("UsersCount " + userRegistry.getUserCount());
return this.userRegistry
.getUsers()
.stream()
.map(SimpUser::getName)
.collect(Collectors.toList());
}
}
But this always gives my an empty list: [] even when obviously WS connections are established.
Is this SimpUserRegistry working with the Websocket system of Spring which is configured with the WebSocketConfigurer and #EnableWebSocket? What am I doing wrong? Any tips or alternatives?
Thank you in advance!

springboot could not found feignclient

ERROR INFO LIKE BELOW:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field helloAgent in com.example.client.controller.Hello required a bean of
type 'com.example.common.agent.HelloAgent' that could not be found.
Action:
Consider defining a bean of type 'com.example.common.agent.HelloAgent' in
your configuration.
project structure:
module: test-client as feignclient caller.
module: test-server as feignclient interface implementation.
module: test-common put all feignclient together.
test-common:
package com.example.common.agent;
#FeignClient("hello")
public interface HelloAgent {
#GetMapping("/hello")
String hello(#RequestParam String msg);
}
test-server:(works fine)
package com.example.server.controller;
#RestController
public class Hello implements HelloAgent {
#Override
public String hello(#RequestParam String msg) {
System.out.println("get " + msg);
return "Hi " + msg;
}
}
test-client:
package com.example.client.controller;
#RestController
public class Hello {
#Autowired
private HelloAgent helloAgent;
#GetMapping("/test")
public String test() {
System.out.println("go");
String ret = helloAgent.hello("client");
System.out.println("back " + ret);
return ret;
}
}
----------------------------
#EnableEurekaClient
#EnableFeignClients
#SpringBootApplication
#ComponentScan(basePackages = {"com.example.common.agent","com.example.client.controller"})
public class TestClientApplication {
public static void main(String[] args) {
SpringApplication.run(TestClientApplication.class, args);
}
}
Is there anyway to put all feignclient together so that we can manage them gracefully?
Or there is only way to use them redundancy?
THANKS!
Feign doesn't know about #ComponentScan.
Use #EnableFeignClients(basePackages = {"com.example.common.agent","com.example.client.controller"})
Solution using Configuration
In case you use Swagger Codegen, you can use a configuration to bootstrap the apis:
#Configuration
public class ParkingPlusFeignClientConfiguration {
#Autowired
private ParkingPlusProperties properties;
#Bean
public ServicoPagamentoTicket2Api ticketApi() {
ApiClient client = new ApiClient();
// https://stackoverflow.com/questions/42751269/feign-logging-not-working/59651045#59651045
client.getFeignBuilder().logLevel(properties.getClientLogLevel());
client.setBasePath(properties.getHost());
// Generated from swagger: https://demonstracao.parkingplus.com.br/servicos
return client.buildClient(ServicoPagamentoTicket2Api.class);
}
}

How to inject property values into Spring Boot beans

In my spring boot application, i'am trying to inject variable's value from the config file application.properties to my java class and i'm getting a null value.
here is the configuration of my application.properties file:
myapp.username=user#user.com
myapp.password=user
here is where i call the configuration entries:
#Component
public class MyClass{
#Value("${myapp.username}")
public String username;
#Value("${myapp.password}")
public String password;
public static void main(String[] args) {
System.out.println(password);
}
}
I hope there someone how did deal with the same problem, thanks.
you can use this example add bean to your config like this :
#Configuration
#ComponentScan(basePackages = "youpackagebase")
#PropertySource(value = { "classpath:application.properties" })
public class AppConfig {
/*
* PropertySourcesPlaceHolderConfigurer Bean only required for #Value("{}") annotations.
* Remove this bean if you are not using #Value annotations for injecting properties.
*/
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
and in your bean :
#Component
public class NetClient {
#Value("${bigwater.api_config.url.login}")
public String url_login;
Best Regards
You are not even letting the Spring Boot container to boot (initialize) as you are are writing the code directly under main.
You should have an Application class as shown below to launch the Spring boot container properly, look here.
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
As far as my understanding you wanted to execute your code once the container is started, so follow the below steps:
Add the above Application class and then in your NetClient component class add a #Postconstruct method & this method will be called automatically once the bean is ready, refer the code below:
#Component
public class NetClient {
#Value("${bigwater.api_config.url.login}")
public String url_login;
#Value("${bigwater.api_config.url.ws}")
public static String url_ws;
#Value("${bigwater.api_config.username}")
public String username;
#Value("${bigwater.api_config.password}")
public String password;
#Postconstruct
public void init() {
//place all of your main(String[] args) method code here
}
//Add authentification() method here
}

Netty-Socketio with Spring MVC

I am trying to add sockets to my Spring MVC project. I think I should wright something in servlet-context.xml but don`t know what. So I create classes
#Component
public class Bootstrap {
#Autowired
private SocketIOServer server;
#PostConstruct
public void start() {
server.start();
}
#PreDestroy
public void stop() {
server.stop();
}
}
and
#Configuration
#ComponentScan("controllers")
public class SpringConfig {
#Bean(name="webSocketServer")
public SocketIOServer webSocketServer() {
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
config.setHostname("localhost");
config.setPort(4443);
final SocketIOServer server = new SocketIOServer(config);
server.addJsonObjectListener(LogFile.class, new DataListener<LogFile>() {
#Override
public void onData(SocketIOClient client, LogFile data, AckRequest ackSender) {
server.getBroadcastOperations().sendJsonObject(data);
}
});
server.addConnectListener(new ConnectListener() {
#Override
public void onConnect(SocketIOClient client) {
LogFile log = new LogFile();
log.setMsg("hello");
server.getBroadcastOperations().sendJsonObject(log);
}
});
return server;
}
}
But nothing gonna work. I added client to resources of project and enter link localhost there and have client on my local machine with right link. But still can`t connect. What I am doing wrong? I believe that I mistaken in configuring beans.
Samples I get from this https://github.com/mrniko/netty-socketio.

Resources