关于Redis缓存集成SSM框架和redis缓存架构的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于CI框架中redis缓存相关操作文件示例代码,ciredis、CI框架中redis缓存相
关于Redis缓存 集成SSM框架和redis缓存架构的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于CI框架中redis缓存相关操作文件示例代码,ciredis、CI框架中redis缓存相关操作文件示例代码,ciredis_PHP教程、django memcached/redis缓存 =====缓存session、Java Redis缓存穿透/缓存雪崩/缓存击穿,Redis分布式锁实现秒杀,限购等等相关知识的信息别忘了在本站进行查找喔。
本文目录一览:- Redis缓存 集成SSM框架(redis缓存架构)
- CI框架中redis缓存相关操作文件示例代码,ciredis
- CI框架中redis缓存相关操作文件示例代码,ciredis_PHP教程
- django memcached/redis缓存 =====缓存session
- Java Redis缓存穿透/缓存雪崩/缓存击穿,Redis分布式锁实现秒杀,限购等
Redis缓存 集成SSM框架(redis缓存架构)
Java SSM 框架集成 Redis框架
<.!-- jedis依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<!-- 连接池基本参数配置,类似数据库连接池 -->
<context:property-placeholder location="classpath:redis.properties"/>
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="1024"/>
<property name="maxIdle" value="200" />
<property name="testOnBorrow" value="true"/>
</bean>
<!-- 连接池配置,类似数据库连接池 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<property name="hostName" value="127.0.0.1"></property>
<property name="port" value="6379"></property>
<!-- <property name="password" value="${redis.pass}"></property> -->
<property name="poolConfig" ref="poolConfig"></property>
</bean>
<bean id="redisCacheTransfer" class="com.jdt.wetalk.redisUtils.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory" />
</bean>
3.编辑Redis.properties 文件
host=127.0.0.1
port=6379
redis.pass=123456
maxIdle=200
maxActive=1024
redis.maxWait=10000
testOnBorrow=true
4.编写一些Redis的辅助类
package com.jdt.wetalk.redisUtils;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean {
private Resource addressConfig;
private String addressKeyPrefix;
private JedisCluster jedisCluster;
private Integer timeout;
private Integer maxRedirections;
private GenericObjectPoolConfig genericObjectPoolConfig;
private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$");
public JedisCluster getObject() throws Exception {
return jedisCluster;
}
public Class<? extends JedisCluster> getObjectType() {
return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
}
public boolean isSingleton() {
return true;
}
private Set<HostAndPort> parseHostAndPort() throws Exception {
try {
Properties prop = new Properties();
prop.load(this.addressConfig.getInputStream());
Set<HostAndPort> haps = new HashSet<HostAndPort>();
for (Object key : prop.keySet()) {
if (!((String) key).startsWith(addressKeyPrefix)) {
continue;
}
String val = (String) prop.get(key);
boolean isIpPort = p.matcher(val).matches();
if (!isIpPort) {
throw new IllegalArgumentException("ip 或 port 不合法");
}
String[] ipAndPort = val.split(":");
HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
haps.add(hap);
}
return haps;
} catch (IllegalArgumentException ex) {
throw ex;
} catch (Exception ex) {
throw new Exception("解析 jedis 配置文件失败", ex);
}
}
public void afterPropertiesSet() throws Exception {
Set<HostAndPort> haps = this.parseHostAndPort();
jedisCluster = new JedisCluster(haps, timeout, maxRedirections, genericObjectPoolConfig);
}
public void setAddressConfig(Resource addressConfig) {
this.addressConfig = addressConfig;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void setMaxRedirections(int maxRedirections) {
this.maxRedirections = maxRedirections;
}
public void setAddressKeyPrefix(String addressKeyPrefix) {
this.addressKeyPrefix = addressKeyPrefix;
}
public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
this.genericObjectPoolConfig = genericObjectPoolConfig;
}
}
2)。RedisCache.java
ackage com.jdt.wetalk.redisUtils;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.exceptions.JedisConnectionException;
public class RedisCache implements Cache {
private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
private static JedisConnectionFactory jedisConnectionFactory;
private final String id;
private final ReadWriteLock rwl = new ReentrantReadWriteLock();
public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
logger.debug("MybatisRedisCache:id=" + id);
this.id = id;
}
/**
* 清空所有缓存
*/
public void clear() {
rwl.readLock().lock();
JedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
connection.flushDb();
connection.flushAll();
logger.debug("清除缓存.......");
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
rwl.readLock().unlock();
}
}
public String getId() {
return this.id;
}
/**
* 获取缓存总数量
*/
public int getSize() {
int result = 0;
JedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
result = Integer.valueOf(connection.dbSize().toString());
logger.info("添加mybaits二级缓存数量:" + result);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
return result;
}
public void putObject(Object key, Object value) {
rwl.writeLock().lock();
JedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
connection.set(SerializeUtil.serialize(key), SerializeUtil.serialize(value));
logger.info("添加mybaits二级缓存key=" + key + ",value=" + value);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
rwl.writeLock().unlock();
}
}
public Object getObject(Object key) {
// 先从缓存中去取数据,先加上读锁
rwl.readLock().lock();
Object result = null;
JedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
result = serializer.deserialize(connection.get(serializer.serialize(key)));
logger.info("命中mybaits二级缓存,value=" + result);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
rwl.readLock().unlock();
}
return result;
}
public Object removeObject(Object key) {
rwl.writeLock().lock();
JedisConnection connection = null;
Object result = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
result = connection.expire(serializer.serialize(key), 0);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
rwl.writeLock().unlock();
}
return result;
}
public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
System.out.println("进入了Redis的获取========");
RedisCache.jedisConnectionFactory = jedisConnectionFactory;
}
public ReadWriteLock getReadWriteLock() {
// TODO Auto-generated method stub
return rwl;
}
}
3)RedisCacheTransfer.java
package com.jdt.wetalk.redisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
public class RedisCacheTransfer {
@Autowired
public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
}
}
4)SerializeUtil.java
4)SerializeUtil.java
package com.jdt.wetalk.redisUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtil {
/**
* 序列化
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 反序列化
*/
public static Object unserialize(byte[] bytes) {
if (bytes != null) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
}
}
return null;
}
}
上面那个 applicationContext.xml 加载 Redis.properties失败 直接在 applicationContext.xml 定义了
CI框架中redis缓存相关操作文件示例代码,ciredis
ci框架中redis缓存相关操作文件示例代码,ciredis
本文实例讲述了ci框架中redis缓存相关操作文件。分享给大家供大家参考,具体如下:
redis缓存类文件位置:
''ci\system\libraries\Cache\drivers\Cache_redis.php''
<?php /** * CodeIgniter * * An open source application development framework for PHP 5.2.4 or newer * * NOTICE OF LICENSE * * Licensed under the Open Software License version 3.0 * * This source file is subject to the Open Software License (OSL 3.0) that is * bundled with this package in the files license.txt / license.rst. It is * also available through the world wide web at this URL: * http://opensource.org/licenses/OSL-3.0 * If you did not receive a copy of the license and are unable to obtain it * through the world wide web, please send an email to * licensing@ellislab.com so we can send you a copy immediately. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) * @link http://codeigniter.com * @since Version 3.0 * @filesource */ defined(''BASEPATH'') OR exit(''No direct script access allowed''); /** * CodeIgniter Redis Caching Class * * @package CodeIgniter * @subpackage Libraries * @category Core * @author Anton Lindqvist <anton@qvister.se> * @link */ class CI_Cache_redis extends CI_Driver { /** * Default config * * @static * @var array */ protected static $_default_config = array( /* ''socket_type'' => ''tcp'', ''host'' => ''127.0.0.1'', ''password'' => NULL, ''port'' => 6379, ''timeout'' => 0 */ ); /** * Redis connection * * @var Redis */ protected $_redis; /** * Get cache * * @param string like *$key* * @return array(hash) */ public function keys($key) { return $this->_redis->keys($key); } /** * Get cache * * @param string Cache ID * @return mixed */ public function get($key) { return $this->_redis->get($key); } /** * mGet cache * * @param array Cache ID Array * @return mixed */ public function mget($keys) { return $this->_redis->mget($keys); } /** * Save cache * * @param string $id Cache ID * @param mixed $data Data to save * @param int $ttl Time to live in seconds * @param bool $raw Whether to store the raw value (unused) * @return bool TRUE on success, FALSE on failure */ public function save($id, $data, $ttl = 60, $raw = FALSE) { return ($ttl) ? $this->_redis->setex($id, $ttl, $data) : $this->_redis->set($id, $data); } /** * Delete from cache * * @param string Cache key * @return bool */ public function delete($key) { return ($this->_redis->delete($key) === 1); } /** * hIncrBy a raw value * * @param string $id Cache ID * @param string $field Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hincrby($key, $field, $value = 1) { return $this->_redis->hIncrBy($key, $field, $value); } /** * hIncrByFloat a raw value * * @param string $id Cache ID * @param string $field Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hincrbyfloat($key, $field, $value = 1) { return $this->_redis->hIncrByFloat($key, $field, $value); } /** * lpush a raw value * * @param string $key Cache ID * @param string $value value * @return mixed New value on success or FALSE on failure */ public function lpush($key, $value) { return $this->_redis->lPush($key, $value); } /** * rpush a raw value * * @param string $key Cache ID * @param string $value value * @return mixed New value on success or FALSE on failure */ public function rpush($key, $value) { return $this->_redis->rPush($key, $value); } /** * rpop a raw value * * @param string $key Cache ID * @param string $value value * @return mixed New value on success or FALSE on failure */ public function rpop($key) { return $this->_redis->rPop($key); } /** * brpop a raw value * * @param string $key Cache ID * @param string $ontime 阻塞等待时间 * @return mixed New value on success or FALSE on failure */ public function brpop($key,$ontime=0) { return $this->_redis->brPop($key,$ontime); } /** * lLen a raw value * * @param string $key Cache ID * @return mixed Value on success or FALSE on failure */ public function llen($key) { return $this->_redis->lLen($key); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function increment($id, $offset = 1) { return $this->_redis->exists($id) ? $this->_redis->incr($id, $offset) : FALSE; } /** * incrby a raw value * * @param string $key Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function incrby($key, $value = 1) { return $this->_redis->incrby($key, $value); } /** * set a value expire time * * @param string $key Cache ID * @param int $seconds expire seconds * @return mixed New value on success or FALSE on failure */ public function expire($key, $seconds) { return $this->_redis->expire($key, $seconds); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hset($alias,$key, $value) { return $this->_redis->hset($alias,$key, $value); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hget($alias,$key) { return $this->_redis->hget($alias,$key); } /** * Increment a raw value * * @param string $id Cache ID * @return mixed New value on success or FALSE on failure */ public function hkeys($alias) { return $this->_redis->hkeys($alias); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hgetall($alias) { return $this->_redis->hgetall($alias); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hmget($alias,$key) { return $this->_redis->hmget($alias,$key); } /** * del a key value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hdel($alias,$key) { return $this->_redis->hdel($alias,$key); } /** * del a key value * * @param string $id Cache ID * @return mixed New value on success or FALSE on failure */ public function hvals($alias) { return $this->_redis->hvals($alias); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hmset($alias,$array) { return $this->_redis->hmset($alias,$array); } /** * Decrement a raw value * * @param string $id Cache ID * @param int $offset Step/value to reduce by * @return mixed New value on success or FALSE on failure */ public function decrement($id, $offset = 1) { return $this->_redis->exists($id) ? $this->_redis->decr($id, $offset) : FALSE; } /** * Clean cache * * @return bool * @see Redis::flushDB() */ public function clean() { return $this->_redis->flushDB(); } /** * Get cache driver info * * @param string Not supported in Redis. * Only included in order to offer a * consistent cache API. * @return array * @see Redis::info() */ public function cache_info($type = NULL) { return $this->_redis->info(); } /** * Get cache metadata * * @param string Cache key * @return array */ public function get_metadata($key) { $value = $this->get($key); if ($value) { return array( ''expire'' => time() + $this->_redis->ttl($key), ''data'' => $value ); } return FALSE; } /** * Check if Redis driver is supported * * @return bool */ public function is_supported() { if (extension_loaded(''redis'')) { return $this->_setup_redis(); } else { log_message(''debug'', ''The Redis extension must be loaded to use Redis cache.''); return FALSE; } } /** * Setup Redis config and connection * * Loads Redis config file if present. Will halt execution * if a Redis connection can''t be established. * * @return bool * @see Redis::connect() */ protected function _setup_redis() { $config = array(); $CI =& get_instance(); if ($CI->config->load(''redis'', TRUE, TRUE)) { $config += $CI->config->item(''redis''); } $config = array_merge(self::$_default_config, $config); $config = !empty($config[''redis''])?$config[''redis'']:$config; $this->_redis = new Redis(); try { if ($config[''socket_type''] === ''unix'') { $success = $this->_redis->connect($config[''socket'']); } else // tcp socket { $success = $this->_redis->connect($config[''host''], $config[''port''], $config[''timeout'']); } if ( ! $success) { log_message(''debug'', ''Cache: Redis connection refused. Check the config.''); return FALSE; } } catch (RedisException $e) { log_message(''debug'', ''Cache: Redis connection refused (''.$e->getMessage().'')''); return FALSE; } if (isset($config[''password''])) { $this->_redis->auth($config[''password'']); } return TRUE; } /** * Class destructor * * Closes the connection to Redis if present. * * @return void */ public function __destruct() { if ($this->_redis) { $this->_redis->close(); } } } /* End of file Cache_redis.php */ /* Location: ./system/libraries/Cache/drivers/Cache_redis.php */
更多关于CodeIgniter相关内容感兴趣的读者可查看本站专题:《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《php缓存技术总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于CodeIgniter框架的PHP程序设计有所帮助。
CI框架中redis缓存相关操作文件示例代码,ciredis_PHP教程
ci框架中redis缓存相关操作文件示例代码,ciredis
本文实例讲述了ci框架中redis缓存相关操作文件。分享给大家供大家参考,具体如下:
redis缓存类文件位置:
''ci\system\libraries\Cache\drivers\Cache_redis.php''
<?php /** * CodeIgniter * * An open source application development framework for PHP 5.2.4 or newer * * NOTICE OF LICENSE * * Licensed under the Open Software License version 3.0 * * This source file is subject to the Open Software License (OSL 3.0) that is * bundled with this package in the files license.txt / license.rst. It is * also available through the world wide web at this URL: * http://opensource.org/licenses/OSL-3.0 * If you did not receive a copy of the license and are unable to obtain it * through the world wide web, please send an email to * licensing@ellislab.com so we can send you a copy immediately. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) * @link http://codeigniter.com * @since Version 3.0 * @filesource */ defined(''BASEPATH'') OR exit(''No direct script access allowed''); /** * CodeIgniter Redis Caching Class * * @package CodeIgniter * @subpackage Libraries * @category Core * @author Anton Lindqvist <anton@qvister.se> * @link */ class CI_Cache_redis extends CI_Driver { /** * Default config * * @static * @var array */ protected static $_default_config = array( /* ''socket_type'' => ''tcp'', ''host'' => ''127.0.0.1'', ''password'' => NULL, ''port'' => 6379, ''timeout'' => 0 */ ); /** * Redis connection * * @var Redis */ protected $_redis; /** * Get cache * * @param string like *$key* * @return array(hash) */ public function keys($key) { return $this->_redis->keys($key); } /** * Get cache * * @param string Cache ID * @return mixed */ public function get($key) { return $this->_redis->get($key); } /** * mGet cache * * @param array Cache ID Array * @return mixed */ public function mget($keys) { return $this->_redis->mget($keys); } /** * Save cache * * @param string $id Cache ID * @param mixed $data Data to save * @param int $ttl Time to live in seconds * @param bool $raw Whether to store the raw value (unused) * @return bool TRUE on success, FALSE on failure */ public function save($id, $data, $ttl = 60, $raw = FALSE) { return ($ttl) ? $this->_redis->setex($id, $ttl, $data) : $this->_redis->set($id, $data); } /** * Delete from cache * * @param string Cache key * @return bool */ public function delete($key) { return ($this->_redis->delete($key) === 1); } /** * hIncrBy a raw value * * @param string $id Cache ID * @param string $field Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hincrby($key, $field, $value = 1) { return $this->_redis->hIncrBy($key, $field, $value); } /** * hIncrByFloat a raw value * * @param string $id Cache ID * @param string $field Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hincrbyfloat($key, $field, $value = 1) { return $this->_redis->hIncrByFloat($key, $field, $value); } /** * lpush a raw value * * @param string $key Cache ID * @param string $value value * @return mixed New value on success or FALSE on failure */ public function lpush($key, $value) { return $this->_redis->lPush($key, $value); } /** * rpush a raw value * * @param string $key Cache ID * @param string $value value * @return mixed New value on success or FALSE on failure */ public function rpush($key, $value) { return $this->_redis->rPush($key, $value); } /** * rpop a raw value * * @param string $key Cache ID * @param string $value value * @return mixed New value on success or FALSE on failure */ public function rpop($key) { return $this->_redis->rPop($key); } /** * brpop a raw value * * @param string $key Cache ID * @param string $ontime 阻塞等待时间 * @return mixed New value on success or FALSE on failure */ public function brpop($key,$ontime=0) { return $this->_redis->brPop($key,$ontime); } /** * lLen a raw value * * @param string $key Cache ID * @return mixed Value on success or FALSE on failure */ public function llen($key) { return $this->_redis->lLen($key); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function increment($id, $offset = 1) { return $this->_redis->exists($id) ? $this->_redis->incr($id, $offset) : FALSE; } /** * incrby a raw value * * @param string $key Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function incrby($key, $value = 1) { return $this->_redis->incrby($key, $value); } /** * set a value expire time * * @param string $key Cache ID * @param int $seconds expire seconds * @return mixed New value on success or FALSE on failure */ public function expire($key, $seconds) { return $this->_redis->expire($key, $seconds); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hset($alias,$key, $value) { return $this->_redis->hset($alias,$key, $value); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hget($alias,$key) { return $this->_redis->hget($alias,$key); } /** * Increment a raw value * * @param string $id Cache ID * @return mixed New value on success or FALSE on failure */ public function hkeys($alias) { return $this->_redis->hkeys($alias); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hgetall($alias) { return $this->_redis->hgetall($alias); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hmget($alias,$key) { return $this->_redis->hmget($alias,$key); } /** * del a key value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hdel($alias,$key) { return $this->_redis->hdel($alias,$key); } /** * del a key value * * @param string $id Cache ID * @return mixed New value on success or FALSE on failure */ public function hvals($alias) { return $this->_redis->hvals($alias); } /** * Increment a raw value * * @param string $id Cache ID * @param int $offset Step/value to add * @return mixed New value on success or FALSE on failure */ public function hmset($alias,$array) { return $this->_redis->hmset($alias,$array); } /** * Decrement a raw value * * @param string $id Cache ID * @param int $offset Step/value to reduce by * @return mixed New value on success or FALSE on failure */ public function decrement($id, $offset = 1) { return $this->_redis->exists($id) ? $this->_redis->decr($id, $offset) : FALSE; } /** * Clean cache * * @return bool * @see Redis::flushDB() */ public function clean() { return $this->_redis->flushDB(); } /** * Get cache driver info * * @param string Not supported in Redis. * Only included in order to offer a * consistent cache API. * @return array * @see Redis::info() */ public function cache_info($type = NULL) { return $this->_redis->info(); } /** * Get cache metadata * * @param string Cache key * @return array */ public function get_metadata($key) { $value = $this->get($key); if ($value) { return array( ''expire'' => time() + $this->_redis->ttl($key), ''data'' => $value ); } return FALSE; } /** * Check if Redis driver is supported * * @return bool */ public function is_supported() { if (extension_loaded(''redis'')) { return $this->_setup_redis(); } else { log_message(''debug'', ''The Redis extension must be loaded to use Redis cache.''); return FALSE; } } /** * Setup Redis config and connection * * Loads Redis config file if present. Will halt execution * if a Redis connection can''t be established. * * @return bool * @see Redis::connect() */ protected function _setup_redis() { $config = array(); $CI =& get_instance(); if ($CI->config->load(''redis'', TRUE, TRUE)) { $config += $CI->config->item(''redis''); } $config = array_merge(self::$_default_config, $config); $config = !empty($config[''redis''])?$config[''redis'']:$config; $this->_redis = new Redis(); try { if ($config[''socket_type''] === ''unix'') { $success = $this->_redis->connect($config[''socket'']); } else // tcp socket { $success = $this->_redis->connect($config[''host''], $config[''port''], $config[''timeout'']); } if ( ! $success) { log_message(''debug'', ''Cache: Redis connection refused. Check the config.''); return FALSE; } } catch (RedisException $e) { log_message(''debug'', ''Cache: Redis connection refused (''.$e->getMessage().'')''); return FALSE; } if (isset($config[''password''])) { $this->_redis->auth($config[''password'']); } return TRUE; } /** * Class destructor * * Closes the connection to Redis if present. * * @return void */ public function __destruct() { if ($this->_redis) { $this->_redis->close(); } } } /* End of file Cache_redis.php */ /* Location: ./system/libraries/Cache/drivers/Cache_redis.php */
更多关于CodeIgniter相关内容感兴趣的读者可查看本站专题:《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《php缓存技术总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于CodeIgniter框架的PHP程序设计有所帮助。
立即学习“PHP免费学习笔记(深入)”;
django memcached/redis缓存 =====缓存session
- 全站使用
例如 博客等缓存,通过中间件实现全站缓存。
加缓存中间件,那么多中间件加在什么位置?
请求时:缓存加在中间件里的最后一个,比如一次经过1、2、3、4中间件,加在4
返回事:缓存加在中间件里的第一个,如上返回依次经过4、3、2、1,加在1
django 中,导入模块,可以实现。
# 使用中间件,经过一系列的认证等操作,
# 如果内容在缓存中存在,则使用FetchFromCacheMiddleware获取内容并返回给用户,
# 当返回给用户之前,判断缓存中是否已经存在,
# 如果不存在则UpdateCacheMiddleware会将缓存保存至缓存,从而实现全站缓存
MIDDLEWARE = [
''django.middleware.cache.UpdateCacheMiddleware'', # 只有process_response # 其他中间件... ''django.middleware.cache.FetchFromCacheMiddleware'', # 只有process_view ] CACHE_MIDDLEWARE_ALIAS = "" CACHE_MIDDLEWARE_SECONDS = "" CACHE_MIDDLEWARE_KEY_PREFIX = ""
2.2 应用多个缓存时生效的优先级
另外:session引擎缓存配置,就是放在这里的缓存里。
如果同时应用了两个级别的缓存,比如views缓存和模板局部缓存,哪个生效?
哪个生效,和请求的声明周期的有关系的
所以最先生效的是全站、之后views、最后模板局部缓存。
django-redis的应用
# =================django-redis============
settings.py配置cache
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100} #最大连接数,redis开启连接池pool
# "PASSWORD": "密码", #redis默认没有密码
}}
}
视图函数中使用
from django_redis import get_redis_connection conn = get_redis_connection("default")缓存session(通过redis/memcache之类)
配置 settings.py
SESSION_ENGINE
=
''django.contrib.sessions.backends.cache''
# 启用cache引擎
SESSION_CACHE_ALIAS
=
''default''
# 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置
SESSION_COOKIE_NAME =
"sessionid"
# Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串
SESSION_COOKIE_PATH =
"/"
# Session的cookie保存的路径
SESSION_COOKIE_DOMAIN
=
None
# Session的cookie保存的域名
SESSION_COOKIE_SECURE
=
False
# 是否Https传输cookie
SESSION_COOKIE_HTTPONLY
=
True
# 是否Session的cookie只支持http传输
SESSION_COOKIE_AGE
=
1209600
# Session的cookie失效日期(2周)
SESSION_EXPIRE_AT_BROWSER_CLOSE
=
False
# 是否关闭浏览器使得Session过期
SESSION_SAVE_EVERY_REQUEST
=
False
# 是否每次请求都保存Session,默认修改之后才保存
from django.core.cache import cache
cache.has_key(''name'')#判断是否有key等于name
cache.set(key,value,timeout=''过期时间'') timeout可选参数
cache.get(key)
Java Redis缓存穿透/缓存雪崩/缓存击穿,Redis分布式锁实现秒杀,限购等
package com.example.redisdistlock.controller;
import com.example.redisdistlock.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class CacheController {
@Autowired
private StringRedisTemplate stringRedisTemplate = null;
@Autowired
private RedisUtil redisUtil = null;
/**
* ****************************** 缓存穿透 ******************************
* 缓存穿透,是指查询一个数据库一定不存在的数据。
* 正常的使用缓存流程大致是,数据查询先进行缓存查询,
* 如果key不存在或者key已经过期,再对数据库进行查询,
* 并把查询到的对象,放进缓存。如果数据库查询对象为空,则不放进缓存。
* 灾难现场:想象一下这个情况,如果传入的参数为-1,会是怎么样?这个-1,就是一定不存在的对象。就会每次都去查询数据库,
* 而每次查询都是空,每次又都不会进行缓存。假如有恶意攻击,就可以利用这个漏洞,对数据库造成压力,甚至压垮数据库。
* 解决方案:如果从数据库查询的对象为空,也放入缓存,只是设定的缓存过期时间较短,比如设置为60秒。
*/
/**
* ****************************** 缓存雪崩 ******************************
* 是指在某一个时间段,缓存集中过期失效。此刻无数的请求直接绕开缓存,直接请求数据库。
* 灾难现场:比如天猫双11,马上就要到双11零点,很快就会迎来一波抢购,这波商品在23点集中的放入了缓存,假设缓存一个小时。
* 那么到了凌晨24点的时候,这批商品的缓存就都过期了。而对这批商品的访问查询,都落到了数据库上,对于数据库而言,就会产生周期性的压力波峰。
* 对数据库造成压力,甚至压垮数据库。
*/
/**
* ****************************** 缓存击穿 ******************************
* 是指一个key非常热点,在不停的扛着大并发,大并发集中对这一个点进行访问,当这个key在失效的瞬间,持续的大并发就穿破缓存,直接请求数据库,就像在一个屏障上凿开了一个洞。
* 灾难现场:比如某个爆款商品(这种爆款很难对数据库服务器造成压垮性的压力。达到这个级别的公司没有几家的。)但我们也要做好防护方案
* 解决方案:对爆款商品都是早早的做好了准备,让缓存永不过期。即便某些商品自己发酵成了爆款,也是直接设为永不过期。
*/
public Object cacheBreakDown(){
Map<String, Object> map = new HashMap<String, Object>();
try {
Object zhangsan = redisUtil.get("zhangsan");
//System.out.println("zhangsan" + zhangsan);
/* 使用双重验证锁解决高并发环境下的缓存穿透问题 */
if (StringUtils.isEmpty(zhangsan)) { // 第一重验证
synchronized (this) {
zhangsan = redisUtil.get("zhangsan");
if (StringUtils.isEmpty(zhangsan)) { // 第二重验证
System.out.println("查询数据库............");
// 缓存为空,则查询数据库将相关数据存储到redis中
redisUtil.set("zhangsan", "张三",10); //10秒后过期
} else {
System.out.println("2 查询缓存............");
}
}
} else {
System.out.println("1 查询缓存............");
}
map.put("success", true);
////entity实体类
//User user = new User();
//user.setUserId(1000);
//user.setUserName("张三");
//user.setAddress("深圳市南山区");
//user.setMobile("13988886666");
//redisUtil.set("userInfo", user.toString(), 10); //10秒后过期自动删除
////获取显示
//String str = String.valueOf(redisUtil.get("userInfo"));
//JSONObject jsonObj = new JSONObject(str);
//map.put("userInfo", jsonObj.get("userId"));
} catch (Exception e) {
map.put("success", false);
e.printStackTrace();
} finally {
}
return map;
}
}
/**
* Redis分布式并发锁(针对业务场景:库存超卖 秒杀 限购等)
*
* @return
*/
@RequestMapping("/reductstore")
@ResponseBody //直接输出字符串
public String ReductStore() {
System.out.println("访问接口");
String lockKey = "lock";
// setnx redisson
RLock lock = redissonClient.getLock(lockKey);
try {
int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock")); lock.lock();
if (stock > 0) {
//业务逻辑减少库存
stringRedisTemplate.opsForValue().set("stock", (stock - 1) + "");
System.out.println("扣减库存成功,库存stock:" + (stock - 1));
} else {
System.out.println("商品已售罄");
}
} catch (NumberFormatException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return "OK";
}
/**
* 单体式架构
*
* @return
*/
@RequestMapping("/reduct")
@ResponseBody //直接输出字符串
public String Reduct() {
//System.out.println("访问接口");
try {
synchronized (this) { //jvm核心技术
int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
if (stock > 0) {
//业务逻辑减少库存
stringRedisTemplate.opsForValue().set("stock", (stock - 1) + "");
System.out.println("扣减库存成功,库存stock:" + (stock - 1));
} else {
System.out.println("商品已售罄");
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
} finally {
}
return "OK";
}
今天关于Redis缓存 集成SSM框架和redis缓存架构的分享就到这里,希望大家有所收获,若想了解更多关于CI框架中redis缓存相关操作文件示例代码,ciredis、CI框架中redis缓存相关操作文件示例代码,ciredis_PHP教程、django memcached/redis缓存 =====缓存session、Java Redis缓存穿透/缓存雪崩/缓存击穿,Redis分布式锁实现秒杀,限购等等相关知识,可以在本站进行查询。
本文标签: