zzh

zzh

Docker links spring project with redis.

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#

image
Where redis.host=redis (we will explain this later).

Start Redis using Docker#
docker run -d redis:alpine

Here we are using a public Docker image directly.

image

Start Spring project using Docker#
  • Create 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).

  • Run 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 to the redis container for communication, rename the redis container name hardcore_nash to redis (this is because in the project's YAML file, 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.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.