1、redis是一个nosql的数据库,操作内存数据,并可以将其存储到硬盘中来持久化
2、与spring的整合 http://www.cnblogs.com/holdouts/articles/5811118.html
需要jar包common-pool2.jar jedis.jar spring-data-redis.jar
spring 配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"></property>
<property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"></property>
<property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"></property>
<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"></property>
</bean>
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
destroy-method="destroy">
<property name="poolConfig" ref="jedisPoolConfig"></property>
<property name="hostName" value="${redis.hostName}"></property>
<property name="port" value="${redis.port}"></property>
<property name="timeout" value="${redis.timeout}"></property>
<property name="usePool" value="${redis.usePool}"></property>
</bean>
<bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> //代表redis的key/value需要序列化 若是实体类,实体类需要实现序列化
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
</bean>
</beans>
@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
<!-- memcached -->
<bean id="memcachedClientBuilder" class="net.rubyeye.xmemcached.XMemcachedClientBuilder"
p:connectionPoolSize="${memcached.connectionPoolSize}" p:failureMode="${memcached.failureMode}">
<!-- XMemcachedClientBuilder have two arguments.First is server list,and second is weights array. -->
<constructor-arg>
<list>
<bean class="java.net.InetSocketAddress">
<constructor-arg>
<value>${server1.memcached.host}</value>
</constructor-arg>
<constructor-arg>
<value>${server1.memcached.port}</value>
</constructor-arg>
</bean>
<bean class="java.net.InetSocketAddress">
<constructor-arg>
<value>${server2.memcached.host}</value>
</constructor-arg>
<constructor-arg>
<value>${server2.memcached.port}</value>
</constructor-arg>
</bean>
</list>
</constructor-arg>
<constructor-arg>
<list>
<value>${server1.memcached.weight}</value>
<value>${server2.memcached.weight}</value>
</list>
</constructor-arg>
<property name="commandFactory">
<bean class="net.rubyeye.xmemcached.command.TextCommandFactory" />
</property>
<property name="sessionLocator">
<bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator" />
</property>
<property name="transcoder">
<bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder" />
</property>
</bean>
<!-- Use factory bean to build memcached client -->
<bean id="memcachedClient" factory-bean="memcachedClientBuilder"
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<Serializable, Serializable> redisTemplate; public void saveUser(final User user) { redisTemplate.execute(new RedisCallback<Object>() { @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<User>() { @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<T> { @Autowired @Qualifier("jedisTemplate") public RedisTemplate redisTemplate; public <T> ValueOperations<String, T> setCacheObject(String key, T value) { ValueOperations<String, T> operation = redisTemplate.opsForValue(); operation.set(key, value); return operation; } public <T> T getCacheObject( String key/* ,ValueOperations<String,T> operation */) { ValueOperations<String, T> operation = redisTemplate.opsForValue(); return operation.get(key); } /** * 缓存List数据 * * @param key * 缓存的键值 * @param dataList * 待缓存的List数据 * @return 缓存的对象 */ public <T> ListOperations<String, T> setCacheList(String key, List<T> 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 <T> List<T> getCacheList(String key) { List<T> dataList = new ArrayList<T>(); ListOperations<String, T> 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 <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet) { BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key); /* * T[] t = (T[]) dataSet.toArray(); setOperation.add(t); */ Iterator<T> it = dataSet.iterator(); while (it.hasNext()) { setOperation.add(it.next()); } return setOperation; } /** * 获得缓存的set * * @param key * @param operation * @return */ public Set<T> getCacheSet( String key/* ,BoundSetOperations<String,T> operation */) { Set<T> dataSet = new HashSet<T>(); BoundSetOperations<String,T> 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 <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if (null != dataMap) { for (Map.Entry<String, T> 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 <T> Map<String, T> getCacheMap( String key/* ,HashOperations<String,String,T> hashOperation */) { Map<String, T> map = redisTemplate.opsForHash().entries(key); /* Map<String, T> map = hashOperation.entries(key); */ return map; } /** * 缓存Map * * @param key * @param dataMap * @return */ public <T> HashOperations<String, Integer, T> setCacheIntegerMap(String key, Map<Integer, T> dataMap) { HashOperations hashOperations = redisTemplate.opsForHash(); if (null != dataMap) { for (Map.Entry<Integer, T> 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 <T> Map<Integer, T> getCacheIntegerMap( String key/* ,HashOperations<String,String,T> hashOperation */) { Map<Integer, T> map = redisTemplate.opsForHash().entries(key); /* Map<String, T> 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<ContextRefreshedEvent> { // 日志 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(" _________ 缓存数据 ________ "); Map<String, Object> params=new HashMap<>(); List<City> cityList = null; List<Country> countryList = null; try { cityList = cityService.getList(" 1=1 ", params); countryList = countryService.getList(" 1=1 ", params); } catch (Exception e) { e.printStackTrace(); } Map<Integer, City> cityMap = new HashMap<Integer, City>(); Map<Integer, Country> countryMap = new HashMap<Integer, Country>(); 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<String,Country> countryMap = * redisCacheUtil1.getCacheMap("country"); Map<String,City> cityMap = * redisCacheUtil.getCacheMap("city"); */ long startTime=System.currentTimeMillis(); Map<Integer, Country> countryMap = redisCache.getCacheIntegerMap("countryMap"); Map<Integer, City> 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()); } } }
<beans xmlns="http://www.springframework.org/schema/beans" 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"> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- <property name="maxIdle" value="6"></property> <property name="minEvictableIdleTimeMillis" value="300000"></property> <property name="numTestsPerEvictionRun" value="3"></property> <property name="timeBetweenEvictionRunsMillis" value="60000"></property> --> <property name="maxIdle" value="${redis.maxIdle}"></property> <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"></property> <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"></property> <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"></property> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="poolConfig" ref="jedisPoolConfig"></property> <property name="hostName" value="${redis.hostName}"></property> <property name="port" value="${redis.port}"></property> <property name="timeout" value="${redis.timeout}"></property> <property name="usePool" value="${redis.usePool}"></property> </bean> <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"></property> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </property> </bean> </beans>
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
作者:DreamerRzc
链接:http://www.jianshu.com/p/7bf5dc61ca06
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
作者:DreamerRzc
链接:http://www.jianshu.com/p/7bf5dc61ca06
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。