Redis+nginx +memcached 网络组件

1、redis是一个nosql的数据库,操作内存数据,并可以将其存储到硬盘中来持久化

2、与spring的整合 http://www.cnblogs.com/holdouts/articles/5811118.html

  需要jar包common-pool2.jar jedis.jar spring-data-redis.jar

  spring 配置文件

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
   default-autowire="byName">
  
  
  
  
  
  

      class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
   destroy-method="destroy">
  
  
  
  
  
  

  
  
  
   //代表redis的key/value需要序列化 若是实体类,实体类需要实现序列化
  

  
  
  

  

  

   @Autowired
  @Qualifier("jedisTemplate")
  public RedisTemplate redisTemplate;

  需要redis的类中,可以注入redisTemplate

  有5种数据操作方式

  redisTemplate.opsForValue();//操作字符串
  redisTemplate.opsForHash();//操作hash
  redisTemplate.opsForList();//操作list
  redisTemplate.opsForSet();//操作set
  redisTemplate.opsForZSet();//操作

3、nginx的安装与部署

  http://blog.csdn.net/kingzma/article/details/46331999
  http://www.runoob.com/linux/nginx-install-setup.html

 cd /home/soft
     yum install openssl   yum install openssl-devel
     yum install zlib-devel yum install zlib
     yum install pcre-devel yum install pcre
下载nginx
wget http://nginx.org/download/nginx-1.13.3.tar.gz
解压   tar -zxvf nginx-1.13.3.tar.gz
重命名 mv nginx-1.33.3 nginx
  安装 c yum install -y gcc gcc-c++
编译nginx  cd /home/soft/nginx
./configure
安装 make make install
默认安装目录 /usr/local/nginx
关闭默认防火墙
systemctl stop firewalld.service #停止firewall
systemctl disable firewalld.service #禁止firewall开机启动
  nginx负载均衡 http://blog.csdn.net/kingzma/article/details/46331999

4、memcached的配置

  http://www.cnblogs.com/mafly/p/memcached.html

  
p:connectionPoolSize="${memcached.connectionPoolSize}" p:failureMode="${memcached.failureMode}">





${server1.memcached.host}


${server1.memcached.port}




${server2.memcached.host}


${server2.memcached.port}






${server1.memcached.weight}
${server2.memcached.weight}













factory-method="build" destroy-method="shutdown" />

需要的缓存的类继承该类变可以

  @Component
  public class MemcachedBasis {
   @Autowired
  protected MemcachedClient memcachedClient;

   protected int Exptime = 3600 * 24;

   protected int DataExptime = this.Exptime * 7;

   protected String Prefix = "SPRINGDEMO:";
  }
5、redis整合代码

package com.longcai.redis.dao.impl;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import com.longcai.redis.User;
import com.longcai.redis.dao.UserDAO;

public class UserDAOImpl  implements UserDAO{
    @Autowired
        public RedisTemplate redisTemplate;

        public void saveUser(final User user) {
            redisTemplate.execute(new RedisCallback() {

                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    connection.set(redisTemplate.getStringSerializer().serialize("user.uid." + user.getId()),
                                   redisTemplate.getStringSerializer().serialize(user.getName()));
                    return null;
                }
            });
        }

        @Override
        public User getUser(final long id) {
            return redisTemplate.execute(new RedisCallback() {
                @Override
                public User doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + id);
                    if (connection.exists(key)) {
                        byte[] value = connection.get(key);
                        String name = redisTemplate.getStringSerializer().deserialize(value);
                        User user = new User();
                        user.setName(name);
                        user.setId(id);
                        return user;
                    }
                    return null;
                }
            });
        }
}

package com.longcai.redistest;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;


/*@Service*/
public class RedisCacheUtil {
    @Autowired
    @Qualifier("jedisTemplate")
    public RedisTemplate redisTemplate;

    public  ValueOperations setCacheObject(String key, T value) {

        ValueOperations operation = redisTemplate.opsForValue();
        operation.set(key, value);
        return operation;
    }

    public  T getCacheObject(
            String key/* ,ValueOperations operation */) {
        ValueOperations operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 缓存List数据
     * 
     * @param key
     *            缓存的键值
     * @param dataList
     *            待缓存的List数据
     * @return 缓存的对象
     */
    public  ListOperations setCacheList(String key, List dataList) {
        ListOperations listOperation = redisTemplate.opsForList();
        if (null != dataList) {
            int size = dataList.size();
            for (int i = 0; i < size; i++) {

                listOperation.rightPush(key, dataList.get(i));
            }
        }

        return listOperation;
    }

    /**
     * 获得缓存的list对象
     * 
     * @param key
     *            缓存的键值
     * @return 缓存键值对应的数据
     */
    public  List getCacheList(String key) {
        List dataList = new ArrayList();
        ListOperations listOperation = redisTemplate.opsForList();
        Long size = listOperation.size(key);

        for (int i = 0; i < size; i++) {
            dataList.add((T) listOperation.leftPop(key));
        }

        return dataList;
    }

    /**
     * 缓存Set
     * 
     * @param key
     *            缓存键值
     * @param dataSet
     *            缓存的数据
     * @return 缓存数据的对象
     */
    public  BoundSetOperations setCacheSet(String key, Set dataSet) {
        BoundSetOperations setOperation = redisTemplate.boundSetOps(key);
        /*
         * T[] t = (T[]) dataSet.toArray(); setOperation.add(t);
         */
    
        Iterator it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }

        return setOperation;
    }

    /**
     * 获得缓存的set
     * 
     * @param key
     * @param operation
     * @return
     */
    public Set getCacheSet(
            String key/* ,BoundSetOperations operation */) {
        Set dataSet = new HashSet();
        BoundSetOperations operation = redisTemplate.boundSetOps(key);

        Long size = operation.size();
        for (int i = 0; i < size; i++) {
            dataSet.add(operation.pop());
        }
        return dataSet;
    }

    /**
     * 缓存Map
     * 
     * @param key
     * @param dataMap
     * @return
     */
    public  HashOperations setCacheMap(String key, Map dataMap) {

        HashOperations hashOperations = redisTemplate.opsForHash();
        if (null != dataMap) {

            for (Map.Entry entry : dataMap.entrySet()) {

                /*
                 * System.out.println("Key = " + entry.getKey() + ", Value = " +
                 * entry.getValue());
                 */
                hashOperations.put(key, entry.getKey(), entry.getValue());
            }

        }

        return hashOperations;
    }

    /**
     * 获得缓存的Map
     * 
     * @param key
     * @param hashOperation
     * @return
     */
    public  Map getCacheMap(
            String key/* ,HashOperations hashOperation */) {
        Map map = redisTemplate.opsForHash().entries(key);
        /* Map map = hashOperation.entries(key); */
        return map;
    }

    /**
     * 缓存Map
     * 
     * @param key
     * @param dataMap
     * @return
     */
    public  HashOperations setCacheIntegerMap(String key, Map dataMap) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        if (null != dataMap) {

            for (Map.Entry entry : dataMap.entrySet()) {

                /*
                 * System.out.println("Key = " + entry.getKey() + ", Value = " +
                 * entry.getValue());
                 */
                hashOperations.put(key, entry.getKey(), entry.getValue());
            }

        }

        return hashOperations;
    }

    /**
     * 获得缓存的Map
     * 
     * @param key
     * @param hashOperation
     * @return
     */
    public  Map getCacheIntegerMap(
            String key/* ,HashOperations hashOperation */) {
        Map map = redisTemplate.opsForHash().entries(key);
        /* Map map = hashOperation.entries(key); */
        return map;
    }
}
package com.longcai.redistest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.longcai.entity.City;
import com.longcai.entity.Country;
import com.longcai.service.CityService;
import com.longcai.service.CountryService;


/*
 * 监听器,用于项目启动的时候初始化信息
 */
/*@Service*/
public class StartAddCacheListener implements ApplicationListener {
    // 日志
    private final Logger log = Logger.getLogger(StartAddCacheListener.class);

    @Autowired
    private RedisCacheUtil redisCache;

    @Autowired
    private CityService cityService;
    
    @Autowired
    private CountryService countryService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // spring 启动的时候缓存城市和国家等信息
        if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) {
            System.out.println("\n\n\n_________\n\n缓存数据 \n\n ________\n\n\n\n");
            Map params=new HashMap<>();
            List cityList = null;
            List countryList = null;
            try {
                cityList = cityService.getList(" 1=1 ", params);
                countryList = countryService.getList(" 1=1 ", params);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Map cityMap = new HashMap();
            Map countryMap = new HashMap();
            int cityListSize = cityList.size();
            int countryListSize = countryList.size();
            for (int i = 0; i < cityListSize; i++) {
                cityMap.put(Integer.valueOf(cityList.get(i).getCityID()), cityList.get(i));
            }
            for (int i = 0; i < countryListSize; i++) {
                countryMap.put(Integer.valueOf(countryList.get(i).getProvinceID()), countryList.get(i));
            }
            System.out.println("--------------------");
            redisCache.setCacheIntegerMap("cityMap", cityMap);
            redisCache.setCacheIntegerMap("countryMap", countryMap);
        }
    }
    

} 
  

package com.longcai.redistest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.longcai.entity.City;
import com.longcai.entity.Country;
import com.longcai.service.CityService;
import com.longcai.service.CountryService;


/*
 * 监听器,用于项目启动的时候初始化信息
 */
/*@Service*/
public class StartAddCacheListener implements ApplicationListener {
    // 日志
    private final Logger log = Logger.getLogger(StartAddCacheListener.class);

    @Autowired
    private RedisCacheUtil redisCache;

    @Autowired
    private CityService cityService;
    
    @Autowired
    private CountryService countryService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // spring 启动的时候缓存城市和国家等信息
        if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) {
            System.out.println("\n\n\n_________\n\n缓存数据 \n\n ________\n\n\n\n");
            Map params=new HashMap<>();
            List cityList = null;
            List countryList = null;
            try {
                cityList = cityService.getList(" 1=1 ", params);
                countryList = countryService.getList(" 1=1 ", params);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Map cityMap = new HashMap();
            Map countryMap = new HashMap();
            int cityListSize = cityList.size();
            int countryListSize = countryList.size();
            for (int i = 0; i < cityListSize; i++) {
                cityMap.put(Integer.valueOf(cityList.get(i).getCityID()), cityList.get(i));
            }
            for (int i = 0; i < countryListSize; i++) {
                countryMap.put(Integer.valueOf(countryList.get(i).getProvinceID()), countryList.get(i));
            }
            System.out.println("--------------------");
            redisCache.setCacheIntegerMap("cityMap", cityMap);
            redisCache.setCacheIntegerMap("countryMap", countryMap);
        }
    }
    

}

package com.longcai.redistest;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.longcai.entity.City;
import com.longcai.entity.Country;
import com.longcai.redis.User;

/*@Controller*/
public class Test {

    @Autowired
    private RedisCacheUtil redisCache;

    @RequestMapping("testGetCache.shtml")
    public void testGetCache() {
        /*
         * Map countryMap =
         * redisCacheUtil1.getCacheMap("country"); Map cityMap =
         * redisCacheUtil.getCacheMap("city");
         */
        
        long startTime=System.currentTimeMillis();
        Map countryMap = redisCache.getCacheIntegerMap("countryMap");
        Map cityMap = redisCache.getCacheIntegerMap("cityMap");
        long endTime=System.currentTimeMillis();
        System.out.println("==================================");
        System.out.println(endTime-startTime);
        System.out.println("==================================");
        for (int key : countryMap.keySet()) {
            System.out.println("key = " + key + ",value=" + countryMap.get(key).toString());
        }

        System.out.println("------------city");
        for (int key : cityMap.keySet()) {
            System.out.println("key = " + key + ",value=" + cityMap.get(key).toString());
        }
    }

}


    
        

        
        
        
        
    
    
        
        
        
        
        
    
    
        
        
            
        
        
            
        
    

redis.hostName=127.0.0.1
redis.port=6379
redis.timeout=15000
redis.usePool=true
 
redis.maxIdle=6
redis.minEvictableIdleTimeMillis=300000
redis.numTestsPerEvictionRun=3
redis.timeBetweenEvictionRunsMillis=60000

参考博客:Redis+nginx +memcached

希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!

你可能感兴趣的:(Linux网络编程,redis,nginx,memcached)