Docker experience under Jedis

jedis is redis java version of client implementation, this paper shows the basic usage jedis through a number of instances of web request & response;

Before you begin coding we first prepare the environment, a total of two server, corresponding to the two docker container:

  1. redis, version 3.2.8 using the redis, this time using a real single redis;
  2. tomcat, using version 7.0.77-jre8, due to the deployment of support online, so tomcat Mirror mirror on the official made a small amount of customization, please refer to "combat docker, write Dockerfile custom tomcat mirror, realize online web application deployment" , where you can not DIY, in hub.docker.com download bolingcavalry / online_deploy_tomcat: 0.0.1 mirror can, in order to support online deployment, servers within a node in the local maven settings.xml environment increases a server node, as follows:
<server>
       <id>tomcat7</id>
       <username>bolingcavalry</username>
       <password>bolingcavalrypswd</password>
     </server>

These are just to be introduced on the environment, do not need their own hands to build one by one, by a docker-compose.yml can build successful, docker-compose.yml document reads as follows:

version: '2'
services:
  redis001: 
    image: daocloud.io/library/redis:3.2.8
    restart: always
  tomcat001: 
    image: bolingcavalry/online_deploy_tomcat:0.0.1
    links: 
      - redis001:redishost
    ports: 
      - "8080:8080"
    environment:
      TOMCAT_SERVER_ID: tomcat_server_001
    restart: always

Open the console, execute the following command in the directory where the docker-compose.yml file:

docker-compose up -d

After the completion of the implementation environment to build successful, in your browser and enter "localhost: 8080" you can see the familiar Home tomcat:

[Image dump in the chain ... (img-dXCPA2Gd-1568682376493)]

OK environment, and can start coding, the source address is Git [email protected]: zq2599 / blog_demos.git, there are a plurality of works herein, this project is used redisdemo, as shown in FIG red box:

Write pictures described here

This is a maven project, first look maven dependent, pom dependency in addition to jedis, plus spring, jstl, common and other commonly used library as follows:

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
            <scope>test</scope>
        </dependency>
        <!-- spring核心包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 导入java ee jar 包 -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
        <!-- JSTL标签类 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 映入JSON -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <!-- 上传组件包 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>

        <!-- redis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

Then web.xml configuration, comprising a spring mvc configuration and extension profiles (spring-extends.xml):

<!-- Spring的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-extends.xml</param-value>
    </context-param>

    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 防止Spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- Spring MVC servlet -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Then there is the java coding, because the web request is made multithreading, multiple threads simultaneously using redis service, so we use the example of jedis connection pool JedisPool to serve concurrent requests jedis provide services at the same time;

A connection pool is enough, so here created a class RedisPool a single embodiment, it functions as follows:

Instantiate a resource pool object Jedis, which is JedisPool;
to provide access to the thread business Jedis Jedis and return service;

Next we look at the key code RedisPool, including instantiation, JedisPool create, retrieve Jedis, the return of Jedis four parts:

Examples of RedisPool:

public static RedisPool getInstance(){
        if(null==instance) {
            synchronized (RedisPool.class){
                if(null==instance){
                    instance = new RedisPool();
                }
            }
        }

        return instance;
    }

When the resource pool following initialization code, attention is ADDR parameter ip redis red box portion of the server, in the present embodiment is connected to the container docker, the value used is the ADDR "redishost", link and when this container start tomcat redis container alias parameters coincide:

Write pictures described here

The following is a method getJedis, taken from a pool of resources Jedis instance to the service thread, since the thread-safe method jedisPool.getResource, so getJedis () may be called simultaneously a plurality of threads without lock operations:

public Jedis getJedis(){
        try {
            if(null!=jedisPool){
                Jedis jedis = jedisPool.getResource();
                return jedis;
            }else{
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

Here is the thread business run out of Jedis instance, the return of the method invoked when to pool resources, attention, jedis this using the 2.9.0 version, so continue to use jedisPool.returnResource, after jedis3.0 version will use the new method to return to the resource pool:

public void returnResource(final Jedis jedis){
        if(jedis!=null){
            //jedis.close()取代jedisPool.returnResource(jedis)方法将3.0版本开始
            jedisPool.returnResource(jedis);
        }
    }

He finished RedisPool, to solve the source of the problem Jedis, then we look at how to use the Jedis:

This article is just getting started, it shows only part of the Jedis services through RedisService provide external interfaces, API as follows:

/**
     * string操作,常规设置key-value
     * @param key
     * @param value
     */
    void strSet(String key, String value);

    /**
     * string操作,常规通过key获取value
     * @param key
     * @return
     */
    String setGet(String key);

    /**
     * list操作,尾部追加数据
     * @param key
     * @param value
     */
    void listAppend(String key, String value);

    /**
     * list操作,获取说有数据
     */
    List<String> listGetAll(String key);

    /**
     * 指定键值在redis中是否存在
     * @param key
     * @return
     */
    boolean exists(String key);

Specific implementation in RedisServiceImpl, we pick out a few to see:

@Override
    public void strSet(String key, String value) {
        Jedis jedis = borrowJedis();

        if(null!=jedis){
            jedis.set(key, value);
        }

        returnJedis(jedis);
    }

    @Override
    public String setGet(String key) {
        Jedis jedis = borrowJedis();

        if(null!=jedis){
            String value = jedis.get(key);
            returnJedis(jedis);
            return value;
        }

        return null;
    }

    @Override
    public void listAppend(String key, String value) {
        Jedis jedis = borrowJedis();

        if(null!=jedis){
            jedis.rpush(key, value);
            returnJedis(jedis);
        }
    }

    @Override
    public List<String> listGetAll(String key) {
        List<String> list = null;

        Jedis jedis = borrowJedis();

        if(null!=jedis){
            list = jedis.lrange(key, 0, -1);
            returnJedis(jedis);
        }

        return null==list ? new ArrayList() : list;
    }

Can be found, the command and redis client api Jedis like is provided, e.g. jedis.get, jedis.lrange etc., can basically find the command operation corresponding to the api.

Look at the last scene of RedisService call, in this case with a spring mvc, so we look at RedisController:

The following four methods represent four inlet url:

@RequestMapping("/simpleset")
    public String simpleset(HttpServletRequest request, Model model) {
        addCommon(model);
        return "simple_set";
    }

    @RequestMapping("/simpleget")
    public String simpleget(HttpServletRequest request, Model model) {
        addCommon(model);
        return "simple_get";
    }

    @RequestMapping("/listappend")
    public String listappend(HttpServletRequest request, Model model) {
        addCommon(model);
        return "list_append";
    }

    @RequestMapping("/listgetall")
    public String listgetall(HttpServletRequest request, Model model) {
        addCommon(model);
        return "list_get_all";
    }

Simpleset to the first example, the browser to http: // localhost: 8080 / redisdemo / simpleset, simpleset corresponding method is invoked, opened simple_get.jsp, as shown below:

Write pictures described here

Enter the key, value, click submit, in due form submission was specified address is strget, so get RedisController method will be called:

@RequestMapping("/strget")
    public String get(HttpServletRequest request, Model model) {
        String key = request.getParameter("key");

        String rlt;

        //判断key在redis中是否存在
        if(redisService.exists(key)){
            rlt = "simple_get_success";
            String value = redisService.setGet(key);

            model.addAttribute("value", value);
        }else{
            rlt = "check";
            model.addAttribute("exists", "不存在");
        }

        model.addAttribute("key", key);

        addCommon(model);
        return rlt;
    }

If the key is present, remove the data, and jump to simple_get_success.jsp page, otherwise jump to check.jsp page, displaying different content.

These are the basic usage Introduction of jedis, please see redisdemo source.

In addition, the deployment of the project, use the command mvn Package Penalty for Clean = -U -Dmaven.test.skip to true tomcat7: the redeploy , the project will be able to compile the package deployed to the tomcat up.

I welcome the attention of the public numbers: programmer Chen Xin

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/bolingcavalry/p/11531533.html