redis注解开发详解

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sortedset –有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

官方网站:http://redis.io/ 
官方下载:http://redis.io/download 可以根据需要下载不同版本 
windows版:https://github.com/ServiceStack/redis-windows

一、引入redis(gradle)

// spring-data-redis
compile group: 'org.springframework.data', name: 'spring-data-redis', version: '1.7.2.RELEASE'
compile group: 'redis.clients', name: 'jedis', version: '2.8.1'

二、配置信息:redis.properties

# Redis Configurations
redis.usePool = true
redis.hostName = 127.0.0.1
redis.port = 6379
redis.timeout = 2000
redis.database =0

三、spring中的配置:applicationContext-redis.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:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache.xsd">

    <context:component-scan base-package="com.mango.service"/>
    <cache:annotation-driven/>

    <context:property-placeholder location="classpath:redis.properties"/>

    <!-- redis链接参数 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="usePool" value="${redis.usePool}"/>
        <property name="hostName" value="${redis.hostName}"/>
        <property name="port" value="${redis.port}"/>
        <property name="timeout" value="${redis.timeout}"/>
        <property name="database" value="${redis.database}"/>
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
    </bean>

    <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg ref="redisTemplate"/>
        <property name="defaultExpiration" value="3000"/>
        <property name="transactionAware" value="true"/>
        <property name="usePrefix" value="true"/>
    </bean>

</beans>

四、加入到spring容器 web.xml

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath*:applicationContext-*.xml</param-value>
</context-param>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

五、启动缓存服务器:redis-server.exe 

六、java代码(本例ssm框架) 
1、定义接口

public interface IRedisService {
    public String cacheable(int key) throws Exception;
    public String cacheEvict(int key) throws Exception;
    public String cachePut(int key) throws Exception;
}

2、实现接口,这里不考虑业务,只返回方法名

@Service
public class RedisServiceImpl implements IRedisService {
    /**
     * 用于查询的注解,第一次查询的时候返回该方法返回值,并向redis服务器保存数据,
     * 以后的查询将不再执行方法体内的代码,而是直接查询redis服务器获取数据并返回。
     * value属性做键,key属性则可以看作为value的子键,
     * 一个value可以有多个key组成不同值存在redis服务器,
     * 这里再介绍一个属性是condition,用法condition="#key<10",
     * 就是说当key小于10的时候才将数据保存到redis服务器
     */
    @Override
    @Cacheable(value="redis",key="#key",condition="#key<10")
    public String cacheable(int key) throws Exception {
        return "cacheable";
    }

    /**
     * 用于更新数据库或新增数据时的注解,更新redis服务器中该value的值
     */
    @Override
    @CachePut(value="redis",key="#key",condition="#key<10")
    public String cachePut(String key) throws Exception {
        return "cachePut";
    }

    /**
     * 用于删除数据操作时的注解,删除redis数据库中该value对应的数据
     */
    @Override
    @CacheEvict(value="redis",key="#key")
    public String cacheEvict(String key) throws Exception {
        return "cacheEvict";
    }
}

3、controller,创建三个测试方法,这里只简单的将文本显示到jsp页面

@Controller
public class PageController {

    @Autowired
    private IRedisService iRedisService;

    @RequestMapping("/cacheable")//查找
    public String cacheable(HttpServletRequest request, 
            HttpServletResponse response) throws Exception{
        int key = Integer.parseInt(request.getParameter("key"));
        String msg = iRedisService.cacheable(key);
        response.getWriter().print(msg);
        return null;
    }
    @RequestMapping("/cachePut")//增改
    public String cachePut(HttpServletRequest request, 
            HttpServletResponse response) throws Exception{
        int key = Integer.parseInt(request.getParameter("key"));
        String msg = iRedisService.cachePut(key);
        response.getWriter().print(msg);
        return null;
    }
    @RequestMapping("/cacheEvict")//删除
    public String cacheEvict(HttpServletRequest request, 
            HttpServletResponse response) throws Exception{
        int key = Integer.parseInt(request.getParameter("key"));
        String msg = iRedisService.cacheEvict(key);
        response.getWriter().print(msg);
        return null;
    }

}

 4、测试 
启动分析器 redis-cli.exe 
执行keys *查询缓存中全部数据,当前为空
启动tomcat服务器,访问/cacheabel,打印结果为cachea
如果将访问的参数改到大于10的数则不会将数据保存到redis
七、如果redis服务器未启动的处理,以查询为例

@RequestMapping("/cacheable")//查找
public String cacheable(HttpServletRequest request, 
        HttpServletResponse response) throws Exception{
    int key = Integer.parseInt(request.getParameter("key"));
    String msg = "";
    //首先访问缓存方法,如果缓存服务器未开启或链接异常则访问未加缓存注解的方法
    try {
        msg = iRedisService.cacheable(key);
    } catch (JedisConnectionException e) {
        msg = iRedisService.未加缓存注解的方法(key);
    } catch (RedisConnectionFailureException e){
        msg = iRedisService.未加缓存注解的方法(key);
    }
    response.getWriter().print(msg);
    return null;
}

八、Redis客户端常用命令 
redis 127.0.0.1:6379> keys * #查看所有key 
redis 127.0.0.1:6379> info #查看server版本内存使用连接等信息 
redis 127.0.0.1:6379> client list #获取客户连接列表 
redis 127.0.0.1:6379> client kill 127.0.0.1:33441 #终止某个客户端连接 
redis 127.0.0.1:6379> dbsize #当前保存key的数量 
redis 127.0.0.1:6379> save #立即保存数据到硬盘 
redis 127.0.0.1:6379> bgsave #异步保存数据到硬盘 
redis 127.0.0.1:6379> flushdb #当前库中移除所有key 
redis 127.0.0.1:6379> flushall #移除所有key从所有库中 
redis 127.0.0.1:6379> lastsave #获取上次成功保存到硬盘的时间戳 
redis 127.0.0.1:6379> monitor #实时监测服务器接收到的请求 
redis 127.0.0.1:6379> slowlog len #查询慢查询日志条数 
redis 127.0.0.1:6379> slowlog get #返回所有的慢查询日志,最大值取决于slowlog-max-len配置 
redis 127.0.0.1:6379> slowlog get 2 #打印两条慢查询日志 
redis 127.0.0.1:6379> slowlog reset #清空慢查询日志信息

猜你喜欢

转载自blog.csdn.net/Keith003/article/details/82016880