Redis学习笔记(三)
来源:互联网 发布:淘宝企业店铺负责人 编辑:程序博客网 时间:2024/06/18 07:35
njb里redis的应用例子:
1、njb/pom.xml文件:
[java] view plain copy
- <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>
[java] view plain copy
- <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:
[java] view plain copy
- <?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>
[java] view plain copy
- <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>
[java] view plain copy
- <property name="host" value="${redis.album.host}" />
[java] view plain copy
- # 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)
[java] view plain copy
- @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对象
[java] view plain copy
- /**
- * 返回详细地址
- */
- 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中保存数据
[java] view plain copy
- @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);
- }
阅读全文
0 0
- redis学习笔记(三)
- Redis学习笔记(三)
- redis学习笔记(三)
- Redis学习笔记(三)
- redis学习笔记(三)
- Redis 学习笔记三
- redis学习笔记三
- Linux学习笔记(三)--redis学习
- Redis学习笔记(三)--事务
- redis 学习笔记三(队列功能)
- redis学习笔记三(队列功能)
- Redis学习笔记(三)java redis 基本操作
- Redis学习笔记(三)Redis源码解读
- redis学习笔记(三)redis数据淘汰策略
- Redis学习笔记(三)Redis源码解读
- Redis学习笔记——(三)Redis集群安装
- Redis学习笔记(三)---对象
- redis学习笔记三(列表)
- UEditor图片文件上传至服务器
- 515. Find Largest Value in Each Tree Row Difficulty: Medium
- Android studio使用debug调试
- UI Automator Viewer的使用
- 黑暗效应、巴纳姆效应、鸟笼逻辑
- Redis学习笔记(三)
- PaddlePaddle 系列之三行代码从入门到精通
- TCP的三次握手、四次挥手--非常详细讲解
- MTK平台NV基本功能与操作
- MYSQL数据库基本操作语句
- SWing中三种最大化初始窗口的方法
- java反转链表
- memcached 安装与端口监控
- 使用pm2启动nodeJS程序