NoSQL Databases (MongoDB, Redis)

 NoSQL Databases: MongoDB and Redis

NoSQL databases provide a flexible schema design and are optimized for specific use cases such as handling large volumes of unstructured data, horizontal scaling, and high performance. Two popular NoSQL databases are MongoDB and Redis. This guide provides an overview of these databases, their use cases, and how to work with them using Java.


MongoDB

MongoDB is a document-oriented NoSQL database that stores data in JSON-like BSON (Binary JSON) format. It is designed for high availability, scalability, and ease of development.


Key Features of MongoDB:

- Schema-less: No predefined schema; each document can have a different structure.

- Scalability: Easy horizontal scaling using sharding.

- High Performance: Optimized for read and write operations.

- Rich Query Language: Supports a variety of query types, including ad-hoc queries, indexing, and real-time aggregation.


Example: Using MongoDB with Java

1. Add Dependencies:

   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-mongodb</artifactId>
   </dependency>


2. Application Configuration (`application.properties`):

   spring.data.mongodb.host=localhost
   spring.data.mongodb.port=27017
   spring.data.mongodb.database=mydatabase


3. Define Entity Class:

   import org.springframework.data.annotation.Id;
   import org.springframework.data.mongodb.core.mapping.Document;

   @Document(collection = "users")
   public class User {
       @Id
       private String id;

       private String name;
       private String email;

       // Getters and setters
   }


4. Repository Interface:

   import org.springframework.data.mongodb.repository.MongoRepository;

   public interface UserRepository extends MongoRepository<User, String> {
   }


5. Service Class:

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.stereotype.Service;

   @Service
   public class UserService {

       @Autowired
       private UserRepository userRepository;

       public List<User> getAllUsers() {
           return userRepository.findAll();
       }

       public User getUserById(String id) {
           return userRepository.findById(id).orElse(null);
       }

       public User saveUser(User user) {
           return userRepository.save(user);
       }

       public void deleteUser(String id) {
           userRepository.deleteById(id);
       }
   }


6. Controller Class:

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.web.bind.annotation.*;
   import java.util.List;

   @RestController
   @RequestMapping("/users")
   public class UserController {

       @Autowired
       private UserService userService;

       @GetMapping
       public List<User> getAllUsers() {
           return userService.getAllUsers();
       }

       @GetMapping("/{id}")
       public User getUserById(@PathVariable String id) {
           return userService.getUserById(id);
       }

       @PostMapping
       public User saveUser(@RequestBody User user) {
           return userService.saveUser(user);
       }

       @DeleteMapping("/{id}")
       public void deleteUser(@PathVariable String id) {
           userService.deleteUser(id);
       }
   }


Redis

Redis is an in-memory key-value store known for its high performance, flexibility, and support for various data structures such as strings, hashes, lists, sets, and sorted sets.


Key Features of Redis:

- In-memory Storage: Fast read and write operations.

- Data Structures: Supports a wide range of data types.

- Persistence: Offers persistence options to disk (RDB and AOF).

- Pub/Sub Messaging: Built-in publish/subscribe functionality.

- Atomic Operations: Supports atomic operations on data structures.


Example: Using Redis with Java

1. Add Dependencies:

   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
   </dependency>


2. Application Configuration (`application.properties`):

   spring.redis.host=localhost
   spring.redis.port=6379


3. Configure Redis Template:

   import org.springframework.context.annotation.Bean;
   import org.springframework.context.annotation.Configuration;
   import org.springframework.data.redis.connection.RedisConnectionFactory;
   import org.springframework.data.redis.core.RedisTemplate;
   import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
   import org.springframework.data.redis.serializer.StringRedisSerializer;

   @Configuration
   public class RedisConfig {

       @Bean
       public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
           RedisTemplate<String, Object> template = new RedisTemplate<>();
           template.setConnectionFactory(connectionFactory);
           template.setKeySerializer(new StringRedisSerializer());
           template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
           return template;
       }
   }


4. Service Class:

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.data.redis.core.RedisTemplate;
   import org.springframework.stereotype.Service;
   import java.util.List;

   @Service
   public class UserService {

       @Autowired
       private RedisTemplate<String, Object> redisTemplate;
       private static final String KEY = "User";

       public void saveUser(User user) {
           redisTemplate.opsForHash().put(KEY, user.getId(), user);
       }

       public User getUserById(String id) {
           return (User) redisTemplate.opsForHash().get(KEY, id);
       }

       public List<Object> getAllUsers() {
           return redisTemplate.opsForHash().values(KEY);
       }

       public void deleteUser(String id) {
           redisTemplate.opsForHash().delete(KEY, id);
       }
   }


5. Controller Class:

   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.web.bind.annotation.*;
   import java.util.List;

   @RestController
   @RequestMapping("/users")
   public class UserController {

       @Autowired
       private UserService userService;

       @PostMapping
       public void saveUser(@RequestBody User user) {
           userService.saveUser(user);
       }

       @GetMapping("/{id}")
       public User getUserById(@PathVariable String id) {
           return userService.getUserById(id);
       }

       @GetMapping
       public List<Object> getAllUsers() {
           return userService.getAllUsers();
       }

       @DeleteMapping("/{id}")
       public void deleteUser(@PathVariable String id) {
           userService.deleteUser(id);
       }
   }


Conclusion

MongoDB and Redis are powerful NoSQL databases suitable for different use cases. MongoDB excels in handling large volumes of unstructured data with flexible schema design, while Redis is ideal for high-performance, in-memory data storage and complex data structures. By integrating these databases with Java and Spring Boot, you can build robust and scalable applications that leverage the strengths of NoSQL databases.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....