Can vertx and traditional jdbc clients work together in quarkus? - quarkus

In my quarkus project, I have added the following dependencies to create a non-blocking asynchronous project
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-vertx</artifactId>
</dependency>
<dependency>
<groupId>io.smallrye.reactive</groupId>
<artifactId>smallrye-mutiny-vertx-web-client</artifactId>
</dependency>
But now I want to write data to mysql database, so I want to add the following dependency to the project
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-mysql</artifactId>
</dependency>
But it seems that this database driver and orm are blocking, so what I want to ask is, does vert.x work with traditional jdbc in quarkus?
Another question is, is the quarkus framework an asynchronous, non-blocking framework? What is its relationship to vert.x? When the qurakus framework Added vert.x dependency, did the whole project require non-blocking?

Quarkus can be reactive or non reactive, it depends which extensions you choose to use.
Hibernate ORM Panache is for when you want to access the database in a non reactive way using Hibernate ORM and Panache.
The same is true for JDBC, it's not reactive so you have to use something else if you want your whole app to be reactive.
In this scenario, you probably want to try these two extensions:
quarkus-hibernate-reactive-panache: See the Hibernate Reactive with panache quickstart for an example
quarkus-reactive-mysql-client: For allowing reactive access to the db. See the guide for Vert.x SQL Clients on the quarkus website
On the Quarkus website, there is also an intro on reactive for Quarkus.
Example of how to use the Vert.x SQL client from the guide:
#Path("fruits")
public class FruitResource {
#Inject
io.vertx.mutiny.mysqlclient.MySQLPool client;
}
client.query("DROP TABLE IF EXISTS fruits").execute()
.flatMap(r -> client.query("CREATE TABLE fruits (id SERIAL PRIMARY KEY, name TEXT NOT NULL)").execute())
.flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Orange')").execute())
.flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Pear')").execute())
.flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Apple')").execute())
.await().indefinitely();
Example with Hibernate Reactive and Panache from the quickstart:
#Entity
public class Fruit extends PanacheEntity {
#Column(length = 40, unique = true)
public String name;
public Fruit() {
}
public Fruit(String name) {
this.name = name;
}
}
#GET
public Uni<List<Fruit>> get() {
return Fruit.listAll(Sort.by("name"));
}
A complete list of quickstarts for Quarkus is available on GitHub.
Look for the ones with the word reactive and you will have several examples with different extensions.
To conclude, one approach is to replace the Hibernate ORM and JDBC extensions with the following:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-reactive-panache</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-reactive-mysql-client</artifactId>
</dependency>
Answer to your questions:
is the quarkus framework an asynchronous, non-blocking framework? What is its relationship to vert.x?
Quarkus is designed to work with popular Java standards, frameworks, and libraries. So, it being reactive or not depends from which extensions you pick and how you design your app. Vert.x is one of the tools that are available to you (See What's Quakrkus?)
When the quarkus framework Added vert.x dependency, did the whole project require non-blocking?
No. For example, you can have both the JDBC driver and the Vert.x SQL client extensions on the classpath and get one or the other via injection when you need to use them.

Related

How to use and config caching in Spring MVC

I want to cache the following getMessagesList method. I want to call one time When user log into the system. Therefor I think caching is the best solution for that. And I need to remove when user log out. How I can do this.
public List<String> getMessagesList(String username)
{ // return messages list in DB by username}
My project was create using Maven 4.0 and Spring MVC. spring version 5.3
Assuming you use Spring Security as part of your app, it should be managing your session, and every time you log out, it will create a new session. Unless you had posted this code, I'm not going to be able to help you there. However, assuming you can log in/out, this should be covered already.
As for the cacheing, in general, this sounds like a Database Caching need, which is something that you would use Spring Boot Caching on.
To use this in Spring Boot, you would add the following dependency to maven (or the equivalent in Gradle, etc):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
Adjust your application to allow using Cacheing, which can be done by adding the annotation #EnableCaching to your Spring Boot application
#SpringBootApplication
#EnableCaching
public class MyApplication {
...
}
Create a Java Service Object, called something like MessagesService.class:
#CacheConfig(cacheNames={"Messages"})
public class MessagesService {
#Cacheable(value="cacheMessages")
List<String> getMessages() {
//access the database to load data here
...
}
...
}

I am not able to connect to Google Cloud Memory Store from Spring Boot

I am developing a module with spring boot in my backend where i need to use Redis through GCP Memory Store. I have been searching in forum and even the "oficial documentation" about memory store but i cannot understand how to connect to memory store with my spring boot app.
I found a google code lab but they use a Compute Engine VM to install spring boot and then save and retrieve information from memory store. So i tried to do it like that in my local spring boot but it didnt work because throws an error saying:
Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to 10.1.3.4
the codelab i mentioned earlier says that you only have to add this line to your application.properties:
spring.redis.host=10.1.3.4
as well as the annotation #EnableCaching in the main class and #Cachable annotation in the controller method where you try to do something with redis.
the method looks like this:
#RequestMapping("/hello/{name}")
#Cacheable("hello")
public String hello(#PathVariable String name) throws InterruptedException {
Thread.sleep(5000);
return "Hello " + name;
}
i dont know what else to do. Notice that i am new on this topic of redis and memory store.
Anyone can give me some guidance on this please?
thanks in advance
codelab url: https://codelabs.developers.google.com/codelabs/cloud-spring-cache-memorystore#0
See this documentation on how to setup Memorystore Redis instance.
Included in the documentation is how you can connect and test your Memorystore instance from different computing environments.
There's also a step by step guide on how SpringBoot can use Redis to cache with annonations.
Add the Spring Data Redis starter in your pom.xml if you're using Maven for your project setup.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Add this configuration in your application.properties file:
spring.redis.host=<MEMORYSTORE_REDIS_IP>
# Configure default TTL, e.g., 10 minutes
spring.cache.redis.time-to-live=600000
Turn on caching capability explicitly with the #EnableCaching annotation:
#SpringBootApplication
#EnableCaching
class DemoApplication {
...
}
Once you configured the Spring Boot with Redis and enabled caching, you can use the #Cacheable annotation to cache return values.
#Service
class OrderService {
private final OrderRepository orderRepository;
public OrderService(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
#Cacheable("order")
public Order getOrder(Long id) {
orderRepository.findById(id);
}
}

How to use OpenApi annotations in spring-webflux RouterFunction endpoints?

I am currently working on a project where I use spring functional web programming. I usually use annotations of swagger 2 in restController but with functional web programming I can not find where ! The place to tell the app to do a search for endpoints (like basepackage in Docket) and load swagger in an html page.
Here is my code:
#Configuration
public class RouterClient{
#Bean
public RouterFunction<ServerResponse> routes(ClientHandler client){
return route(GET("/api/client"), client::findAll)
.andRoute(POST("/api/client"),client::add);
}
}
Config Class:
#Configuration
public class OpenApiConfiguration{
#Bean
public GroupedOpenApi groupOpenApi() {
String paths[] = {"/api/**"};
String packagesToscan[] = {"com.demo.client"};
return GroupedOpenApi.builder().setGroup("groups").pathsToMatch(paths).packagesToScan(packagesToscan)
.build();
}
}
The dependencies:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webflux-core</artifactId>
<version>1.2.32</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webflux-ui</artifactId>
<version>1.2.32</version>
</dependency>
The result :
Functional endpoints are supported since 1.3.8 (early May). See releases on GitHub.
Have a look at this: https://springdoc.org/#spring-webfluxwebmvc-fn-with-functional-endpoints
The easiest way to see your endpoints on the Swagger UI is to add the #RouterOperation annotation to your RouterFunction methods (containing a single route), and specify the beanClass and beanMethod used in it. However, in your case, there are multiple routes on a single method, so you must also use the #RouterOperations annotation. These cases are well documented in the link above.
It seems like the current implementation of springdoc-openapi only allows to manually add the documentation.
set
springdoc.api-docs.enabled=false
This will skip classpath scanning (springfox) for the API annotations. (OAS3 replaced these in v3) and replace them with reading in the spec file (json/yaml).
Put the documentation in the Spec files, as one can generate any number of clients from these. Easiest way to start with legacy code is to copy the /api-docs/ files generated by springfox.
You can go to editor.swagger.io, load in the version 2 yaml and convert it to version 3 if springfox still doesn't do that. Then work with yaml files. (it's a contract UP-Front specification for a reason)
https://springdoc.org/
You need springdoc-openapi-webflux-ui and #RouterOperation.
spring-webflux with Functional Endpoints, will be available in the future release

Spring Data Projection not working

I want to use spring projection in my project. I am doing exactly as mentioned at this url http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
interface NoAddresses {
String getFirstName();
String getLastName();
}
The only difference is my interface is public. and is not in the same package as the repository. Is that a requirement?
Still I see the whole entities are being returned, instead of just the projected columns.
I have
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.2.RELEASE</version>
</dependency>
Doesn't work. Do i need to add some dependency to make the projection work? I am not using spring-boot but just the spring-data stuff in my project, running on tomcat server.
thanks
Chahat

WildFly 10, JCache - method caching

i have simple application using Spring Boot. I wanted allow method caching with JSR107 - JCache. So with help of tutorial i put together this code :
#CacheResult(cacheName = "testpoc")
public Country getCountry(Integer id){
System.out.println("---> Loading country with code '" + id + "'");
return new Country(id, "X", "Title");
}
with this POM file
...
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
...
(dependency 'spring-boot-starter-web' is there for simple REST service which call getCountry method)
Everything works like documentations says - method is invoked only once.
Now i wanted to try it on WildFly 10 application server
I have modified pom file :
excluded tomcat
exluded spring-boot-starter-cache
added infinispan-jcache (because i want to use cache configured / managed by wildfly in standalone/domain.xml)
Check pom file here on pastebin.
Problem is, that i am receiving following error :
Cannot find cache named 'java:jboss/infinispan/app-cache'
(i have tried to use both JNDI assigned and name to infinispan cache configured in wildfly).
Following code created Cache object (so i can used it) :
CacheManager cacheManager = Caching.getCachingProvider().getCacheManager();
Cache<String, String> cache = cacheManager.createCache("testpoc", new MutableConfiguration<String, String>());
Question :
It is possible to use JCache method caching on WildFly 10 using Infinispan managed by WildFly ?
Or Infinispan should be used for method caching like JCache, hence JCache has "more functionality" than Infinispan.
Thank you very much
PS :It is not problem for me to put whole code on github and post link - it is few lines of code ...
There are a couple of problems with your approach so let me go through them in steps.
At first you need to use proper Infinispan setup. Infinispan bits shipped with WF should be considered as internal or private. In order to use Infinispan in your app properly - either add org.infinispan:infinispan-embedded to your deployment or install Infinispan Wildfly modules. You can find installation guide here (it's a bit outdated but still, the procedure is exactly the same - unpack modules into WF and use Dependencies MANIFEST.MF entry).
Once you have successfully installed Infinispan (or added it to your app), you need to consider whether you want to use Spring Cache or JCache. If you're only interested in using annotations - I would recommend the former since it's much easier to setup (all you need to do is to add #EnableCaching to one of your configurations). Finally with Spring Cache you will create an Infinispan CacheManager bean. An example can be found here.
Final note - if you still need to use JCache - use this manual to setup Caching Provider.

Resources