In this article, we will be creating a simple CRUD spring boot application and integrating it with Redis Cache using annotations.
Let’s consider a scenario, we are building a web application for an e-commerce platform. We have created API’s for showing products, offers, categories on the home page of our application. If we created these API’s without using any cache then every time a request will come, data will be fetched from the database. In that case, If our application is being used by millions of users at a time then we can face multiple issues like performance of website decreases, loading time increases, load on server as well as database etc. So in that case If we added caching for API’s, then only for first request data will be fetched from the database. Whenever other requests will come data will be directly served from Cache. In this, there will be no execution of query on database, data will be directly fetched from cache (in-memory store), application response time will be increased and we can give faster user experience.
Above is the one scenario we discussed, but there are multiple scenarios in which we can use caching for that.
Before going further in this article we will look at common terminologies like Redis and Jedis.
Redis, which stands for Remote Dictionary Server, is an open-source in-memory data store written in C. It’s often used as a database, cache, and may be used as a message broker.
Data is going to be stored in Redis within the simple key-value pairs where the key is used to extract values. Redis allows us to store different types of data structures like strings, lists, maps, sets, bitmaps, streams, spatial indexes.
Redis is usually used for cache management by microservices to reduce the number of database calls to the server.
To define connections settings from application client to Redis server, we need Redis client which will be helpful to interact with Redis server; it’s something similar to JdbcTemplate to connect with MySql Server.
Installing Redis
You can easily set up a Redis server on the machine using the following command
Ubuntu 18.04 LTS & 20.04 LTS $ sudo apt install redis-server macOS, you can install it via brew. $ brew install redis
After successfully installing the redis-server package, let’s check the status of the Redis process to verify the installation:
$ sudo systemctl status redis
The result shows the status of the redis-server, the bind-address and the port on which redis-server is listening on:
redis-server.service - Advanced key-value store Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)` Active: active (running) since Tue 2020-01-19 10:06:30 UTC; 3min 2s ago Docs: http://redis.io/documentation, man:redis-server(1) Main PID: 2227 (redis-server) Tasks: 4 (limit: 1152) CGroup: /system.slice/redis-server.service └─2227 /usr/bin/redis-server 127.0.0.1:6379
By default, the Redis configuration will be available in the /etc/redis/redis.conf file.
By default, Redis is accessible only from localhost. To enable remote connection to our Redis server, update the bind-address in Redis configuration to 0.0.0.0:
bind 0.0.0.0 ::1
Once updated, restart it:
$ systemctl restart redis
We can use spring-boot-starter-data-redis maven artifact provided by Spring boot to integrate Redis with the spring boot project. Below are the maven dependencies that we require for the integration.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
We need to configure spring data redis in the application.properties file for hostname, port number
spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.cache.redis.cache-null-values=false spring.cache.redis.time-to-live=600000
Also, use the @EnableCaching annotation on Spring Boot main class:
@SpringBootApplication @EnableCaching public class SpringBootRedisExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRedisExampleApplication.class, args); } }
Create a simple User class that includes first name, last name, email and mobile. Added Lombok dependency. It is providing helpful annotations like @NoArgsConstructor, @AllArgsConstructor, and @Data instead of generating getters and setters in our code itself.
@Entity @DynamicUpdate @Data @NoArgsConstructor public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") private Integer userId; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "email") private String email; @Column(name = "mobile") private String mobile; }
In that UserDto class is a simple model class that includes only getters. Always use a model class to accept the request body rather than an entity class.
@RestController public class UserController { @Autowired private UserService userService; @PostMapping("add-user") public ResponseEntity<UserModel> addUser(@RequestBody UserDto userDto) { UserModel userModel = userService.addUser(userDto); return new ResponseEntity<UserModel>(userModel, HttpStatus.OK); } @GetMapping("users/{userId}") public ResponseEntity<UserModel> getUser(@PathVariable Integer userId) { UserModel userModel = userService.getUser(userId); return new ResponseEntity<UserModel>(userModel, HttpStatus.OK); } @DeleteMapping("users/{userId}") public ResponseEntity<String> deleteUser(@PathVariable Integer userId) { userService.deleteUser(userId); return new ResponseEntity<String>("User deleted successfully", HttpStatus.OK); } @GetMapping("users") public ResponseEntity<List<UserModel>> allUsers(@RequestParam(defaultValue = "1") Integer page) { List<UserModel> userModels = userService.allUsers(page); return new ResponseEntity<List<UserModel>>(userModels, HttpStatus.OK); } }
@Getter public class UserDto { private String firstName; private String lastName; private String email; private String mobile; }
We will create a custom mapper class for converting a source class object to a destination class object. Added ModelMapper dependency for that. You can use any other dependency for doing the conversion.
@Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Autowired private Mapper mapper; @Override public UserModel addUser(UserDto userDto) { User user = mapper.convert(userDto, User.class); return mapper.convert(userDao.saveUser(user), UserModel.class); } @Override public UserModel getUser(Integer userId) { User user = userDao.userById(userId); return mapper.convert(user, UserModel.class); } @Override public void deleteUser(Integer userId) { userDao.deleteUser(userId); } @Override public List<UserModel> allUsers(Integer page) { return mapper.convertToList(userDao.allUsers(page), UserModel.class); } }
@Component public class Mapper { public <T> T convert(Object srcObj, Class<T> targetClass) { T response = null; ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setAmbiguityIgnored(true); try { response = modelMapper.map(srcObj, targetClass); } catch (Exception e) { throw new CustomException(e.getMessage(), 500); } return response; } public <S, T> List<T> convertToList(List<S> srcList, Class<T> targetClass) { List<T> response = new ArrayList<>(); ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setAmbiguityIgnored(true); try { srcList.stream().forEach(source -> response.add(modelMapper.map(source, targetClass))); } catch (Exception e) { throw new CustomException(e.getMessage(), 500); } return response; } }
We will add caching in the DAO layer using @CachePut, @CacheEvict, @Cacheable, @Caching annotations.
The reason we are going to use the DAO layer for caching is that sometimes we need to do some operations on results in the service layer based on parameters passed or we can call the same methods from different locations. It’s better to maintain a separate DAO layer for caching purposes and others too.
Let’s see how to add caching on methods.
First, we will create two methods one is for adding users and the other is for getting users by id.
@Override @Caching(evict = { @CacheEvict(value = "usersList", allEntries = true), }, put = { @CachePut(value = "user", key = "#user.getUserId()") }) public User saveUser(User user) { try { return userRepo.save(user); } catch (Exception e) { throw new CustomException("Error while saving user", 500); } } @Override @Cacheable(value = "user", key = "#userId") public User userById(Integer userId) { return userRepo.findByUserId(userId).orElseThrow(() -> new CustomException("User not found", 400)); }
In the saveUser() method, We have added @CachePut annotation for updating or adding the particular entity in the cache, and @CacheEvict is used because If we have created a cache for users list then if the user is updated or deleted then we are going to evict or flush the cache with the given value to makes sure that it should also update in Redis Cache.
In the userById() method, we have used @Cacheable annotation with key as “userId” and value as “user”. So that when this method is called, a record of the user with userId will be stored in Redis cache.
So, Let’s see this by calling the API from Postman.
Before calling add-user API first open the terminal and run the below command to view whether the record is inserted in the Redis cache or not.
$ redis-cli monitor
Call the add-user API from the postman with the user required fields.
After calling the API we will be able to see the logs below in redis-cli monitor. That means the record is successfully added to the Redis cache with given key and values.
You can see the “SET” operation with value and key as “user::1”. It means the user is stored in Redis cache.
Now we will call “users/{userId}” ex. “users/1” API to get the user details by Id.
In redis-cli logs, We can see the “GET” operation with key-value as “user::1”.
There is no “SET” operation performed. But when you explicitly run the redis-cli flushall command or cache expires then after calling the same API, the first “SET” operation is called, and then the “GET” operation is called.
Consider there are thousands of records in the database and you want to return the records based on the pagination. In that case, we will do caching for a list of records using the key as page number and value as usersList.
By doing so we can achieve a faster response in terms of accessing records on the basis of pagination.
For this, we will create a method that will return a list of users.
@Override @Cacheable(value = "usersList", key = "#page") public List<User> allUsers(Integer page) { Page<User> users = userRepo.findAll(PageRequest.of(--page, 5)); if (users.isEmpty()) { throw new CustomException("Users not found", 400); } return users.getContent(); }
In the above method, we have added @Cacheable annotation with value as “usersList” and key as “page”.
Now let’s call the users list API.
Check the redis-cli monitor logs in the terminal.
If some data is to be deleted from the actual Database, there won’t be a point to keep it in cache anymore. We can clear cache data using @CacheEvict annotation.
@Override @Caching(evict = { @CacheEvict(value = "usersList", allEntries = true), @CacheEvict(value = "user", key = "#userId"), }) public void deleteUser(Integer userId) { try { userRepo.deleteById(userId); } catch (Exception e) { throw new CustomException("Error while deleting user", 500); } }
In the deleteUser() method, we have added an array of @CacheEvict as we have maintained a users list array.
Let’s do this by calling delete user API.
We can see below logs in redis-cli as the user record is deleted for id.
We learned a lot in this article. We installed the Redis server on a machine, we have created a spring boot application using annotations like @Cacheable, @Caching, @CachePut, and @CacheEvict.
In case you have some questions feel free to write to us 🙂
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork