Redis学习笔记(三)
2015-11-18 10:53
585 查看
njb里redis的应用例子:
<profiles>
<!-- ================= Database Profiles ================= -->
<profile>
<id>test189</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- Database settings -->
<jdbc.url>jdbc:mysql://183.56.132.189/njb?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8&autoReconnect=true</jdbc.url>
<jdbc.username>njb</jdbc.username>
<jdbc.password>njb2015</jdbc.password>
......//省略很多
<redis.album.host>183.56.132.189</redis.album.host>
<redis.album.port>6379</redis.album.port>
<redis.album.password/>
<redis.album.database>0</redis.album.database>
<redis.contactbook.host>183.56.132.189</redis.contactbook.host>
<redis.contactbook.port>6379</redis.contactbook.port>
<redis.contactbook.password/>
<redis.contactbook.database>1</redis.contactbook.database>
<redis.loginuser.host>183.56.132.189</redis.loginuser.host>
<redis.loginuser.port>6379</redis.loginuser.port>
<redis.loginuser.password/>
<redis.loginuser.database>2</redis.loginuser.database>
<redis.price.host>183.56.132.189</redis.price.host>
<redis.price.port>6379</redis.price.port>
<redis.price.password/>
<redis.price.database>3</redis.price.database>
<redis.readlog.host>183.56.132.189</redis.readlog.host>
<redis.readlog.port>6379</redis.readlog.port>
<redis.readlog.password/>
<redis.readlog.database>4</redis.readlog.database>
<redis.other.host>183.56.132.189</redis.other.host>
<redis.other.port>6379</redis.other.port>
<redis.other.password/>
<redis.other.database>5</redis.other.database>
<redis.notice.host>183.56.132.189</redis.notice.host>
<redis.notice.port>6379</redis.notice.port>
<redis.notice.password/>
<redis.notice.database>6</redis.notice.database>
......
</properties>
</profile>
......
</properties>
并且redis.properties:
(2)从redis中取数据并转化为vo对象
(3)向redis中保存数据
1、njb/pom.xml文件:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.36</version> </dependency>
<profiles>
<!-- ================= Database Profiles ================= -->
<profile>
<id>test189</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- Database settings -->
<jdbc.url>jdbc:mysql://183.56.132.189/njb?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8&autoReconnect=true</jdbc.url>
<jdbc.username>njb</jdbc.username>
<jdbc.password>njb2015</jdbc.password>
......//省略很多
<redis.album.host>183.56.132.189</redis.album.host>
<redis.album.port>6379</redis.album.port>
<redis.album.password/>
<redis.album.database>0</redis.album.database>
<redis.contactbook.host>183.56.132.189</redis.contactbook.host>
<redis.contactbook.port>6379</redis.contactbook.port>
<redis.contactbook.password/>
<redis.contactbook.database>1</redis.contactbook.database>
<redis.loginuser.host>183.56.132.189</redis.loginuser.host>
<redis.loginuser.port>6379</redis.loginuser.port>
<redis.loginuser.password/>
<redis.loginuser.database>2</redis.loginuser.database>
<redis.price.host>183.56.132.189</redis.price.host>
<redis.price.port>6379</redis.price.port>
<redis.price.password/>
<redis.price.database>3</redis.price.database>
<redis.readlog.host>183.56.132.189</redis.readlog.host>
<redis.readlog.port>6379</redis.readlog.port>
<redis.readlog.password/>
<redis.readlog.database>4</redis.readlog.database>
<redis.other.host>183.56.132.189</redis.other.host>
<redis.other.port>6379</redis.other.port>
<redis.other.password/>
<redis.other.database>5</redis.other.database>
<redis.notice.host>183.56.132.189</redis.notice.host>
<redis.notice.port>6379</redis.notice.port>
<redis.notice.password/>
<redis.notice.database>6</redis.notice.database>
......
</properties>
</profile>
......
</properties>
2、njb-service/src/main/resources/applicationContext-resources.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:drools="http://drools.org/schema/drools-spring" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://drools.org/schema/drools-spring http://drools.org/schema/drools-spring-1.3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--读取文本配置文件--> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true" /> <property name="properties" ref="configProperties" /> </bean> <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:mail.properties</value> <value>classpath:hibernate.properties</value> <value>classpath:influxdb.properties</value> <value>classpath:redis.properties</value> <value>classpath:config.properties</value> </list> </property> </bean> ........//JDBC之类很多配置 <bean id="jedisPoolConfig" class="com.eshore.njb.util.JedisPoolConfigWrapper"> <!--最大连接数 --> <property name="maxActive" value="500" /> <!--最大空闲连接数 --> <property name="maxIdle" value="5" /> <!--初始化连接数 --> <property name="minIdle" value="1" /> <!--最大等待时间 --> <property name="maxWait" value="5000" /> <!--对拿到的connection进行validateObject校验 --> <property name="testOnBorrow" value="true" /> <!--在进行returnObject对返回的connection进行validateObject校验 --> <property name="testOnReturn" value="true" /> <!--定时对线程池中空闲的链接进行validateObject校验 --> <property name="testWhileIdle" value="true" /> </bean> <!--除了albumJedisConnection,还有contactbookJedisConnection,loginuserJedisConnection,priceJedisConnection等等连接redis多个数据库的配置--> <bean id="albumJedisConnection" class="com.eshore.framework.utils.JedisConnectionConfigWrapper"> <property name="host" value="${redis.album.host}" /> <property name="port" value="${redis.album.port}" /> <property name="timeout" value="5000" /> <property name="password" value="${redis.album.password}" /> <property name="database" value="${redis.album.database}" /> </bean>
<span style="white-space:pre"> </span><!--在需要的地方注入的就是albumJedisPool,或者otherJedisPool之类的--> <bean id="albumJedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy"> <constructor-arg name="poolConfig"> <bean factory-bean="jedisPoolConfig" factory-method="getConfig" /> </constructor-arg> <constructor-arg name="host"> <bean factory-bean="albumJedisConnection" factory-method="getHost" /> </constructor-arg> <constructor-arg name="port"> <bean factory-bean="albumJedisConnection" factory-method="getPort" /> </constructor-arg> <constructor-arg name="timeout"> <bean factory-bean="albumJedisConnection" factory-method="getTimeout" /> </constructor-arg> <constructor-arg name="password"> <bean factory-bean="albumJedisConnection" factory-method="getPassword" /> </constructor-arg> <constructor-arg name="database"> <bean factory-bean="albumJedisConnection" factory-method="getDatabase" /> </constructor-arg> </bean> ...... </beans>
<property name="host" value="${redis.album.host}" />上文中${redis.album.host}应该引用的是pom.xml中的配置
并且redis.properties:
# Redis settings redis.host=${redis.host} redis.port=${redis.port} redis.keyword.ip=${redis.keyword.ip} redis.keyword.port=${redis.keyword.port} redis.maxIdle=300 redis.maxActive=600 redis.maxWait=1000 redis.testOnBorrow=true
3、使用例子
(1)@Service("albumRedisInitService") public class AlbumRedisInitServiceImpl implements AlbumRedisInitService { Logger logger = Logger.getLogger(this.getClass()); @Resource(name = "albumJedisPool") private JedisPool jedisPool; //一个方法: ...... /** * 相册广场的条目 */ private void initPublicAlbum() { String sql = "select id from album_item where open_type = 1 and del_flag = 0"; Date staDate = new Date(); List<Map<String, Object>> list = appUserDao.findBySQL(sql, new ArrayList<>()); Date endDate = new Date(); System.out.println("find user FocusAlbum cost time :" + (endDate.getTime() - staDate.getTime()) + "ms ,total count:" + list.size()); Jedis jedis = null; try { jedis = jedisPool.getResource(); Pipeline pipeline = jedis.pipelined();//管道(Pipelining)异步方式,一次发送多个指令,不同步等待其返回结果。这样可以取得非常好的执行效率 int i = 1; for (Map<String, Object> map : list) { String id = map.get("id").toString(); //向public_album这个set集合中添加数据 <span style="background-color: rgb(255, 0, 0);">pipeline.sadd("public_album", id);//向public_album这个set集合中添加数据</span> if (i % 10000 == 0) { pipeline.sync();//关闭pipeline } i++; } pipeline.sync();//关闭pipeline System.out.println("insert initPublicAlbum redis cost: " + (new Date().getTime() - endDate.getTime()) + "ms"); } catch (Exception e) { jedisPool.returnBrokenResource(jedis); throw e; } finally { jedisPool.returnResource(jedis); } } ...... }
(2)从redis中取数据并转化为vo对象
/** * 返回详细地址 */ public String getLocationDesc(int locationId, int startLevel, int endLevel) { Jedis jedis = null; try { jedis = jedisPool.getResource(); String locationDesc = ""; String json = jedis.hget("location_detail", locationId + ""); if (json == null) { return null; } RedisLocationVo vo = JSONObject.toJavaObject(JSONObject.parseObject(json), RedisLocationVo.class); if (vo.getLevelType() < startLevel) { return vo.getText(); } if (vo.getLevelType() >= startLevel && vo.getLevelType() <= endLevel) { locationDesc = vo.getText() + locationDesc; } boolean hasParent = true; int id = vo.getPid(); do { String key = "location_parent:" + id; Set<String> set = jedis.zrange(key, 0, -1); if (set != null && !set.isEmpty()) { hasParent = true; <span style="background-color: rgb(255, 0, 0);">json = jedis.hget(location_detail, id + "");//hash的get:hget</span> <span style="background-color: rgb(255, 0, 0);">vo = JSONObject.toJavaObject(JSONObject.parseObject(json), RedisLocationVo.class);</span> id = vo.getPid(); if (vo.getLevelType() >= startLevel && vo.getLevelType() <= endLevel) { locationDesc = vo.getText() + locationDesc; } } else { hasParent = false; } } while (hasParent); return locationDesc; } catch (Exception e) { jedisPool.returnBrokenResource(jedis); throw e; } finally { jedisPool.returnResource(jedis); } }
(3)向redis中保存数据
@Override public void saveWeather() { // TODO Auto-generated method stub //RedisUtil redis = new RedisUtil(); // redis.delOject(weatherKey);// 此处不删除缓存,只更新 // 获取所有市级及内蒙所有县及所有县直辖市 String hql = "from Location l where l.levelType=3 or ( l.levelType=4 and l.parent.parent.id=14727) or (l.levelType=4 and l.parent.id in(33979,57359,35518,41613) ) order by l.levelType "; // or // l.levelType=4 List<Location> list = locationDAO.findByHQL(hql); Properties p = new Properties(); try { ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); InputStream inputStream = classLoader .getResourceAsStream("baiduCityWeather.properties"); p.load(inputStream); } catch (Exception ex) { log.error("获取百度城市名称异常:" + ex.getMessage()); } String noResult = ""; // 获取百度天气 Jedis jedis = null; jedis = jedisPool.getResource(); try { for (Location location : list) { String field = location.getId().toString(); String cityName = location.getName(); // 判断是否需要转换城市名称 if (p.get(location.getId().toString()) != null) { cityName = (String) p.get(location.getId().toString()); } // try { WeatherCacheVo result = getBaiduWeather(cityName); // 由于百度天气根据名称能获取县级天气,故现在调整为不使用天气网接口,天气网接口也经常获取天气失败 // 如果已获取到天气则写入缓存 if (result != null) { log.info("已获取到天气:地区名称:" + cityName + ",地区编号:" + field); <span style="background-color: rgb(255, 0, 0);">String strWeather = JSONObject.toJSONString(result); jedis.hset("weather", field, strWeather);</span> } else { log.error("未获取到天气:地区名称:" + location.getParent().getName() + "/" + cityName); noResult = noResult + location.getId() + "/" + location.getParent().getName() + "/" + cityName + "/" + field + ","; } } catch (Exception ex) { log.error("获取百度天气异常,地区名称:" + cityName); } } } catch (Exception ex) { jedisPool.returnBrokenResource(jedis); } finally { if (jedis != null) { jedisPool.returnResource(jedis); } } log.error("未获取到天气的有:" + noResult); }
相关文章推荐
- RESTful登录设计(基于Spring及Redis的Token鉴权)
- mysql 和 redis的区别
- 15天玩转redis —— 第四篇 哈希对象类型
- Redis学习笔记(二)
- Redis学习手册(事务)
- redis 安装过程
- Redis的配置
- Redis的安装与使用
- redis性能监控
- Redis序列化存储Java集合List等自定义类型
- Redis序列化存储Java集合List等自定义类型
- Redis序列化存储Java集合List等自定义类型
- Redis监控方案
- Redis总结(二)C#中如何使用redis
- 内存替换redis hll
- redis集群方案总结
- redis缓存技术学习 www.iigrowing.cn/redis-huan-cun-ji-shu-xue-xi.html
- mysql保障数据一致性:redis与mysql数据同步(二)
- 初学Redis(2)——用Redis作为Mysql数据库的缓存
- (转) Redis 遇到的坑