Code Implementation#
@RestController
public class HelloWorldTest {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping(path = "/info")
@ResponseBody
public String info(){
return "hello world!";
}
@GetMapping(path = "/getRedis/{key}")
@ResponseBody
public String get(@PathVariable(value = "key") String key){
return redisTemplate.opsForValue().get(key).toString();
}
@GetMapping(path = "/setRedis/{key}/{value}")
@ResponseBody
public String set(@PathVariable(value = "key") String key, @PathVariable(value = "value") String value){
redisTemplate.opsForValue().set(key, value);
return "ok";
}
}
YAML File Configuration#
Where redis.host=redis (we will explain this later).
Starting Redis using Docker#
docker run -d redis:alpine
Here we are using a public Docker image directly.
Starting Spring Project using Docker#
- Creating a custom image using Dockerfile
Dockerfile:
FROM java:8
COPY ./HelloWoldTest-1.0-SNAPSHOT.jar /tmp/app.jar
# Expose port
EXPOSE 8081
# Entry point, the startup command for the Java project
ENTRYPOINT java -jar /tmp/app.jar
Here we are using the custom image java:8 as the base image (which contains the JDK 1.8 image, you can create it yourself if needed).
- Running the Spring project
docker run -d --link hardcore_nash:redis -p 8081:8081 zzh_project:1.0 java -jar /tmp/app.jar
Here we need to link the Redis container for communication, renaming the Redis container name hardcore_nash to redis (because in our project, the yml file has redis.host=redis). This will complete the communication.
Notes#
In Docker, you can also use docker-compose to link two containers. Although they can communicate, if the Redis container has not fully started and the Spring project starts, it will not be able to connect to Redis and will throw an error.