Spring Boot Applications Using Redis Cache
As the subtitle suggests, using Redis cache in Spring Boot applications is quite simple. In this article, we will explore how to add Redis cache to a Spring Boot application.
Adding Redis Cache to a Spring Boot Application
To add Redis cache to a Spring Boot application, we need to add the following dependency to our pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
We also need to add the following configuration to our application.properties file:
spring.redis.password=
spring.redis.database=0
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.host=localhost
spring.redis.timeout=0
With this configuration, we can use the StringRedisTemplate to read and write operations on Redis.
Using StringRedisTemplate
We can use the StringRedisTemplate to save and retrieve string values from Redis:
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void test() throws Exception {
// Save the string
stringRedisTemplate.opsForValue().set("aaa", "111");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa").toString());
}
Serializing and Deserializing Objects
To store objects in Redis, we need to implement our own RedisSerializer<T> interface for serialization and deserialization of the object.
public class User implements Serializable {
private static final long serialVersionUID = -1L;
private String username;
// ...
}
public class RedisObjectSerializer implements RedisSerializer<Object> {
private Converter<Object, byte[]> serializer = new SerializingConverter();
private Converter<byte[], Object> deserializer = new DeserializingConverter();
static final byte[] EMPTY_ARRAY = new byte[0];
public Object deserialize(byte[] bytes) {
if (isEmpty(bytes)) {
return null;
}
try {
return deserializer.convert(bytes);
} catch (Exception ex) {
throw new SerializationException("Can not deserialize", ex);
}
}
public byte[] serialize(Object object) {
if (object == null) {
return EMPTY_ARRAY;
}
try {
return serializer.convert(object);
} catch (Exception ex) {
return EMPTY_ARRAY;
}
}
private boolean isEmpty(byte[] data) {
return (data == null || data.length == 0);
}
}
Using RedisTemplate
We can use the RedisTemplate to save and retrieve objects from Redis:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, User> userRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, User> template = new RedisTemplate<String, User>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}
}
@Autowired
private RedisTemplate<String, User> redisTemplate;
@Test
public void test() throws Exception {
// Save the object
User user = new User("Superman", 20);
redisTemplate.opsForValue().set(user.getUsername(), user);
user = new User("Batman", 30);
redisTemplate.opsForValue().set(user.getUsername(), user);
user = new User("Spider", 40);
redisTemplate.opsForValue().set(user.getUsername(), user);
Assert.assertEquals(20L, redisTemplate.opsForValue().get("Superman").getAge().longValue());
Assert.assertEquals(30L, redisTemplate.opsForValue().get("Batman").getAge().longValue());
Assert.assertEquals(40L, redisTemplate.opsForValue().get("Spider").getAge().longValue());
}
Spring Boot Applications Using RabbitMQ
As the subtitle suggests, using RabbitMQ in Spring Boot applications is quite simple. In this article, we will explore how to add RabbitMQ to a Spring Boot application.
Adding RabbitMQ to a Spring Boot Application
To add RabbitMQ to a Spring Boot application, we need to add the following dependency to our pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
We also need to add the following configuration to our application.properties file:
spring.rabbitmq.password=123456
spring.rabbitmq.port=5672
spring.rabbitmq.host=localhost
spring.rabbitmq.username=spring
Configure Advanced Message Queues
We can use the Queue class to configure advanced message queues, switches, routing, etc.
@Configuration
public class RabbitConfig {
@Bean
public Queue helloQueue() {
return new Queue("hello");
}
}
Using AmqpTemplate
We can use the AmqpTemplate to send and receive messages:
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String context = "hello" + new Date();
System.out.println("Sender:" + context);
this.rabbitTemplate.convertAndSend("hello", context);
}
Using RabbitListener
We can use the RabbitListener to receive messages:
@Component
@RabbitListener(queues = "hello")
public class Receiver {
@RabbitHandler
public void process(String hello) {
System.out.println("Receiver:" + hello);
}
}
Application of Spring Boot Image Packaged into Docker
As the subtitle suggests, packaging a Spring Boot application into a Docker image is quite simple. In this article, we will explore how to package a Spring Boot application into a Docker image.
Adding Docker to a Spring Boot Application
To add Docker to a Spring Boot application, we need to add the docker-maven-plugin to our pom.xml file:
<build>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>VERSION GOES HERE</version>
<configuration>
<imageName>example</imageName>
<baseImage>java</baseImage>
<entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
</plugins>
</build>
Using Docker
We can use the docker-maven-plugin to package our Spring Boot application into a Docker image:
<build>
<plugins>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>VERSION GOES HERE</version>
<configuration>
<imageName>example</imageName>
<baseImage>java</baseImage>
<entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
</plugins>
</build>
CentOS 7 Manual Setting DNS Server
As the subtitle suggests, manually setting a DNS server on CentOS 7 is quite simple. In this article, we will explore how to manually set a DNS server on CentOS 7.
Modifying /etc/NetworkManager/NetworkManager.conf
We can modify the /etc/NetworkManager/NetworkManager.conf file to disable DNS caching:
sudo vim /etc/NetworkManager/NetworkManager.conf
Add the following line to the file:
dns=none
Reloading the Configuration
We can reload the configuration by running the following command:
sudo systemctl restart NetworkManager.service
Manually Modifying /etc/resolv.conf
We can manually modify the /etc/resolv.conf file to set the DNS server:
sudo vim /etc/resolv.conf
Add the following lines to the file:
nameserver 114.114.114.114
nameserver 8.8.8.8
Professional Bash Scripts
As the subtitle suggests, writing professional bash scripts is quite simple. In this article, we will explore how to write professional bash scripts.
Using getopts
We can use the getopts command to parse the input parameters:
#!/bin/bash
while getopts ":h" opt
do
case $opt in
h)
usage
;;
esac
done
Using usage
We can use the usage function to print the script instructions:
usage() {
echo "bla bla bla ..."
}
Writing the Script
We can write the script as follows:
#!/bin/bash
# Parse parameters
while getopts ":h" opt
do
case $opt in
h)
usage
;;
esac
done
# Check parameters
if [ "$1" == "-h" ]; then
usage
exit 0
fi
# Do work
do_work_step1
do_work_step2
do_work_step3
# Main function
main() {
parse_args
validate_args
do_work_step1
do_work_step2
do_work_step3
}
# Script entry function
main
Magical Swagger Document
As the subtitle suggests, using Swagger document to expose API documentation is quite magical. In this article, we will explore how to use Swagger document to expose API documentation.
Using Swagger Editor
We can use the Swagger Editor to easily generate a node.js server version of the server stub:
swagger-editor
Using Swagger UI
We can use the Swagger UI to easily generate a client code language:
swagger-ui
Using Docker
We can use the Docker to easily deploy the API:
docker run -d --name swagger-docs -p 8888:8080 -e 'URLS=[{url: "http://petstore.swagger.io/v2/swagger.json", name: "Petstore"}, {url: "http://generator.swagger.io/api/swagger.json", name: "Generator"}]' swaggerapi/swagger-ui:latest
Note: This is a rewritten version of the original text, with all technical details, terminology, code snippets, and numbers exactly as in the original.