You have hands-on on the basics of how to download and setup a Spring Boot Application using the Spring Initializr tool into your IDE (any of VS Code, IntelliJ, Eclipse or Netbeans)
Also, have an understanding of adding dependencies to your project which can be Gradle or Maven based.
Step 1: Setting up your Spring Boot + Redis Project Dependencies
Make sure you add the Redis dependency to your Spring Boot Project.
Step 3: Redis SET and GET Command Examples with Spring Boot
Just like working with Spring Boot JDBCTemplate, we have a class called RedisTemplate which we can make use of to perform SET and GET commands via Java code.
To keep the example simple, we will implement ApplicationRunner our class with @SpringBootApplication and override the run() method and write our code there.
package com.example.redisdemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootApplication
public class RedisSetGetDemoApplication implements ApplicationRunner {
@Autowired
public RedisTemplate redisTemplate;
public static void main(String[] args) {
SpringApplication.run(RedisSetGetDemoApplication.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
//SET Example: SET message Hello
redisTemplate.opsForValue().set("message", "Hello");
//GET Example: GET message
System.out.println(redisTemplate.opsForValue().get("message"));
}
}
As you would have seen in the above code, to make use of SET, we use the method opsForValue().set() from the RedisTemplate, and similarly opsForValue().get() for GET Command.
Output:
Hello
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
Thanks for your feedback! If you have time, please provide details by selecting options below.
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!