Redis学习笔记(三)

来源:互联网 发布:淘宝企业店铺负责人 编辑:程序博客网 时间:2024/06/18 07:35

njb里redis的应用例子:

1、njb/pom.xml文件:

[java] view plain copy
  1. <dependency>    
  2.         <groupId>redis.clients</groupId>    
  3.         <artifactId>jedis</artifactId>    
  4.         <version>2.1.0</version>    
  5.     </dependency>   
  6. <dependency>  
  7.     <groupId>com.alibaba</groupId>  
  8.     <artifactId>fastjson</artifactId>  
  9.     <version>1.1.36</version>  
  10. </dependency>  

[java] view plain copy
  1. <profiles>  
  2.     <!-- ================= Database Profiles ================= -->  
  3.     <profile>  
  4.         <id>test189</id>  
  5.          <activation>  
  6.                <activeByDefault>true</activeByDefault>  
  7.            </activation>  
  8.         <properties>  
  9.             <!-- Database settings -->  
  10.             <jdbc.url>jdbc:mysql://183.56.132.189/njb?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true</jdbc.url>  
  11.             <jdbc.username>njb</jdbc.username>  
  12.             <jdbc.password>njb2015</jdbc.password>  
  13.             ......//省略很多  
  14.             <redis.album.host>183.56.132.189</redis.album.host>  
  15.             <redis.album.port>6379</redis.album.port>  
  16.             <redis.album.password/>  
  17.             <redis.album.database>0</redis.album.database>  
  18.             <redis.contactbook.host>183.56.132.189</redis.contactbook.host>  
  19.             <redis.contactbook.port>6379</redis.contactbook.port>  
  20.             <redis.contactbook.password/>  
  21.             <redis.contactbook.database>1</redis.contactbook.database>  
  22.             <redis.loginuser.host>183.56.132.189</redis.loginuser.host>  
  23.             <redis.loginuser.port>6379</redis.loginuser.port>  
  24.             <redis.loginuser.password/>  
  25.             <redis.loginuser.database>2</redis.loginuser.database>  
  26.             <redis.price.host>183.56.132.189</redis.price.host>  
  27.             <redis.price.port>6379</redis.price.port>  
  28.             <redis.price.password/>  
  29.             <redis.price.database>3</redis.price.database>  
  30.             <redis.readlog.host>183.56.132.189</redis.readlog.host>  
  31.             <redis.readlog.port>6379</redis.readlog.port>  
  32.             <redis.readlog.password/>  
  33.             <redis.readlog.database>4</redis.readlog.database>  
  34.             <redis.other.host>183.56.132.189</redis.other.host>  
  35.             <redis.other.port>6379</redis.other.port>  
  36.             <redis.other.password/>  
  37.             <redis.other.database>5</redis.other.database>  
  38.             <redis.notice.host>183.56.132.189</redis.notice.host>  
  39.             <redis.notice.port>6379</redis.notice.port>  
  40.             <redis.notice.password/>  
  41.             <redis.notice.database>6</redis.notice.database>  
  42.             ......  
  43.         </properties>  
  44.     </profile>  
  45.     ......  
  46. </properties>  

2、njb-service/src/main/resources/applicationContext-resources.xml:

[java] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mongo="http://www.springframework.org/schema/data/mongo"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"  
  5.     xmlns:cache="http://www.springframework.org/schema/cache"  
  6.     xmlns:context="http://www.springframework.org/schema/context"  
  7.     xmlns:drools="http://drools.org/schema/drools-spring" xmlns:p="http://www.springframework.org/schema/p"  
  8.     xmlns:c="http://www.springframework.org/schema/c"  
  9.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  10.             http://www.springframework.org/schema/data/mongo    http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd  
  11.             http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd  
  12.             http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd  
  13.             http://www.springframework.org/schema/aop     
  14.            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  15.            http://drools.org/schema/drools-spring   
  16.            http://drools.org/schema/drools-spring-1.3.0.xsd  
  17.            http://www.springframework.org/schema/context   
  18.            http://www.springframework.org/schema/context/spring-context.xsd">  
  19.     <!--读取文本配置文件-->  
  20.     <bean id="propertyConfigurer"  
  21.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  22.         <property name="ignoreUnresolvablePlaceholders" value="true" />  
  23.         <property name="properties" ref="configProperties" />  
  24.     </bean>  
  25.   
  26.     <bean id="configProperties"  
  27.         class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  28.         <property name="locations">  
  29.             <list>  
  30.                 <value>classpath:jdbc.properties</value>  
  31.                 <value>classpath:mail.properties</value>  
  32.                 <value>classpath:hibernate.properties</value>  
  33.                 <value>classpath:influxdb.properties</value>  
  34.                 <value>classpath:redis.properties</value>  
  35.                 <value>classpath:config.properties</value>  
  36.             </list>  
  37.         </property>  
  38.     </bean>  
  39.     ........//JDBC之类很多配置  
  40.     <bean id="jedisPoolConfig" class="com.eshore.njb.util.JedisPoolConfigWrapper">  
  41.         <!--最大连接数 -->  
  42.         <property name="maxActive" value="500" />  
  43.         <!--最大空闲连接数 -->  
  44.         <property name="maxIdle" value="5" />  
  45.         <!--初始化连接数 -->  
  46.         <property name="minIdle" value="1" />  
  47.         <!--最大等待时间 -->  
  48.         <property name="maxWait" value="5000" />  
  49.         <!--对拿到的connection进行validateObject校验 -->  
  50.         <property name="testOnBorrow" value="true" />  
  51.         <!--在进行returnObject对返回的connection进行validateObject校验 -->  
  52.         <property name="testOnReturn" value="true" />  
  53.         <!--定时对线程池中空闲的链接进行validateObject校验 -->  
  54.         <property name="testWhileIdle" value="true" />  
  55.     </bean>  
  56.     <!--除了albumJedisConnection,还有contactbookJedisConnection,loginuserJedisConnection,priceJedisConnection等等连接redis多个数据库的配置-->  
  57.     <bean id="albumJedisConnection" class="com.eshore.framework.utils.JedisConnectionConfigWrapper">  
  58.         <property name="host" value="${redis.album.host}" />  
  59.         <property name="port" value="${redis.album.port}" />  
  60.         <property name="timeout" value="5000" />  
  61.         <property name="password" value="${redis.album.password}" />  
  62.         <property name="database" value="${redis.album.database}" />  
  63.     </bean>  
[java] view plain copy
  1. <span style="white-space:pre">    </span><!--在需要的地方注入的就是albumJedisPool,或者otherJedisPool之类的-->  
  2.     <bean id="albumJedisPool" class="redis.clients.jedis.JedisPool"  
  3.         destroy-method="destroy">  
  4.         <constructor-arg name="poolConfig">  
  5.             <bean factory-bean="jedisPoolConfig" factory-method="getConfig" />  
  6.         </constructor-arg>  
  7.         <constructor-arg name="host">  
  8.             <bean factory-bean="albumJedisConnection" factory-method="getHost" />  
  9.         </constructor-arg>  
  10.         <constructor-arg name="port">  
  11.             <bean factory-bean="albumJedisConnection" factory-method="getPort" />  
  12.         </constructor-arg>  
  13.         <constructor-arg name="timeout">  
  14.             <bean factory-bean="albumJedisConnection" factory-method="getTimeout" />  
  15.         </constructor-arg>  
  16.         <constructor-arg name="password">  
  17.             <bean factory-bean="albumJedisConnection" factory-method="getPassword" />  
  18.         </constructor-arg>  
  19.         <constructor-arg name="database">  
  20.             <bean factory-bean="albumJedisConnection" factory-method="getDatabase" />  
  21.         </constructor-arg>  
  22.     </bean>  
  23.     ......  
  24. </beans>  
[java] view plain copy
  1. <property name="host" value="${redis.album.host}" />  
上文中${redis.album.host}应该引用的是pom.xml中的配置

并且redis.properties:
[java] view plain copy
  1. # Redis settings    
  2. redis.host=${redis.host}  
  3. redis.port=${redis.port}  
  4. redis.keyword.ip=${redis.keyword.ip}  
  5. redis.keyword.port=${redis.keyword.port}  
  6. redis.maxIdle=300    
  7. redis.maxActive=600    
  8. redis.maxWait=1000    
  9. redis.testOnBorrow=true  

3、使用例子

(1)
[java] view plain copy
  1. @Service("albumRedisInitService")  
  2. public class AlbumRedisInitServiceImpl implements AlbumRedisInitService {  
  3.     Logger logger = Logger.getLogger(this.getClass());  
  4.     @Resource(name = "albumJedisPool")  
  5.     private JedisPool jedisPool;  
  6.     //一个方法:  
  7.     ......  
  8.      /** 
  9.      * 相册广场的条目 
  10.      */  
  11.     private void initPublicAlbum() {  
  12.         String sql = "select id from album_item where open_type = 1 and del_flag = 0";  
  13.         Date staDate = new Date();  
  14.         List<Map<String, Object>> list = appUserDao.findBySQL(sql,  
  15.             new ArrayList<>());  
  16.         Date endDate = new Date();  
  17.         System.out.println("find user FocusAlbum cost time :" +  
  18.             (endDate.getTime() - staDate.getTime()) + "ms ,total count:" +  
  19.             list.size());  
  20.         Jedis jedis = null;  
  21.         try {  
  22.             jedis = jedisPool.getResource();  
  23.             Pipeline pipeline = jedis.pipelined();//管道(Pipelining)异步方式,一次发送多个指令,不同步等待其返回结果。这样可以取得非常好的执行效率  
  24.             int i = 1;  
  25.             for (Map<String, Object> map : list) {  
  26.                 String id = map.get("id").toString();  
  27.                 //向public_album这个set集合中添加数据  
  28.                 <span style="background-color: rgb(255, 0, 0);">pipeline.sadd("public_album", id);//向public_album这个set集合中添加数据</span>  
  29.                 if (i % 10000 == 0) {  
  30.                     pipeline.sync();//关闭pipeline  
  31.                 }  
  32.                 i++;  
  33.             }  
  34.             pipeline.sync();//关闭pipeline  
  35.             System.out.println("insert initPublicAlbum redis cost: " +  
  36.                 (new Date().getTime() - endDate.getTime()) + "ms");  
  37.         } catch (Exception e) {  
  38.             jedisPool.returnBrokenResource(jedis);  
  39.             throw e;  
  40.         } finally {  
  41.             jedisPool.returnResource(jedis);  
  42.         }  
  43.     }  
  44.     ......  
  45. }  

(2)从redis中取数据并转化为vo对象
[java] view plain copy
  1. /** 
  2.  * 返回详细地址 
  3.  */  
  4. public String getLocationDesc(int locationId, int startLevel, int endLevel) {  
  5.       
  6.     Jedis jedis = null;  
  7.     try {  
  8.         jedis = jedisPool.getResource();  
  9.         String locationDesc = "";  
  10.         String json = jedis.hget("location_detail", locationId + "");  
  11.         if (json == null) {  
  12.             return null;  
  13.         }  
  14.         RedisLocationVo vo = JSONObject.toJavaObject(JSONObject.parseObject(json), RedisLocationVo.class);  
  15.         if (vo.getLevelType() < startLevel) {  
  16.             return vo.getText();  
  17.         }  
  18.         if (vo.getLevelType() >= startLevel && vo.getLevelType() <= endLevel) {  
  19.             locationDesc = vo.getText() + locationDesc;  
  20.         }  
  21.           
  22.         boolean hasParent = true;  
  23.         int id = vo.getPid();  
  24.         do {  
  25.             String key = "location_parent:" + id;  
  26.             Set<String> set = jedis.zrange(key, 0, -1);  
  27.             if (set != null && !set.isEmpty()) {  
  28.                 hasParent = true;  
  29.                 <span style="background-color: rgb(255, 0, 0);">json = jedis.hget(location_detail, id + "");//hash的get:hget</span>  
  30.                 <span style="background-color: rgb(255, 0, 0);">vo = JSONObject.toJavaObject(JSONObject.parseObject(json), RedisLocationVo.class);</span>  
  31.                 id = vo.getPid();  
  32.                 if (vo.getLevelType() >= startLevel && vo.getLevelType() <= endLevel) {  
  33.                     locationDesc = vo.getText() + locationDesc;  
  34.                 }  
  35.             } else {  
  36.                 hasParent = false;  
  37.             }  
  38.         } while (hasParent);  
  39.         return locationDesc;  
  40.     } catch (Exception e) {  
  41.         jedisPool.returnBrokenResource(jedis);  
  42.         throw e;  
  43.     } finally {  
  44.         jedisPool.returnResource(jedis);  
  45.     }  
  46.       
  47. }  

(3)向redis中保存数据
[java] view plain copy
  1. @Override  
  2. public void saveWeather() {  
  3.     // TODO Auto-generated method stub  
  4.     //RedisUtil redis = new RedisUtil();  
  5.     // redis.delOject(weatherKey);// 此处不删除缓存,只更新  
  6.   
  7.     // 获取所有市级及内蒙所有县及所有县直辖市  
  8.     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  
  9.                                                                                                                                                                                  // l.levelType=4  
  10.     List<Location> list = locationDAO.findByHQL(hql);  
  11.   
  12.     Properties p = new Properties();  
  13.     try {  
  14.         ClassLoader classLoader = Thread.currentThread()  
  15.             .getContextClassLoader();  
  16.         InputStream inputStream = classLoader  
  17.             .getResourceAsStream("baiduCityWeather.properties");  
  18.         p.load(inputStream);  
  19.     } catch (Exception ex) {  
  20.         log.error("获取百度城市名称异常:" + ex.getMessage());  
  21.     }  
  22.     String noResult = "";  
  23.     // 获取百度天气  
  24.     Jedis jedis = null;  
  25.     jedis = jedisPool.getResource();  
  26.     try {  
  27.         for (Location location : list) {  
  28.             String field = location.getId().toString();  
  29.             String cityName = location.getName();  
  30.             // 判断是否需要转换城市名称  
  31.             if (p.get(location.getId().toString()) != null) {  
  32.                 cityName = (String) p.get(location.getId().toString());  
  33.             }  
  34.             //  
  35.             try {  
  36.                 WeatherCacheVo result =  getBaiduWeather(cityName);  
  37.                 // 由于百度天气根据名称能获取县级天气,故现在调整为不使用天气网接口,天气网接口也经常获取天气失败  
  38.                 // 如果已获取到天气则写入缓存  
  39.                 if (result != null) {  
  40.                     log.info("已获取到天气:地区名称:" + cityName + ",地区编号:" + field);  
  41.                     <span style="background-color: rgb(255, 0, 0);">String strWeather = JSONObject.toJSONString(result);  
  42.                     jedis.hset("weather", field, strWeather);</span>  
  43.   
  44.                 } else {  
  45.                     log.error("未获取到天气:地区名称:" + location.getParent().getName() + "/" + cityName);  
  46.                     noResult = noResult + location.getId() + "/" + location.getParent().getName() + "/" + cityName + "/" + field + ",";  
  47.                 }  
  48.             } catch (Exception ex) {  
  49.                 log.error("获取百度天气异常,地区名称:" + cityName);  
  50.             }  
  51.         }  
  52.     } catch (Exception ex) {  
  53.         jedisPool.returnBrokenResource(jedis);  
  54.           
  55.     } finally {  
  56.         if (jedis != null) {  
  57.             jedisPool.returnResource(jedis);  
  58.         }  
  59.     }  
  60.     log.error("未获取到天气的有:" + noResult);  
  61. }  
原创粉丝点击