我们目前的系统已经实现了广告后台管理和广告前台展示,但是对于首页每天有大量的人访问,对数据库造成很大的访问压力,甚至是瘫痪。那如何解决呢?我们通常的做法有两种:一种是数据缓存、一种是网页静态化

1. Redis介绍

1.1 Redis

redis 是一款开源的 Key-Value 数据库,运行在内存中,由 ANSIC 编写。企业开发通常采用 Redis 来实现缓存。同类的产品还有 memcache 、memcached 、MongoDB 等

1.2 Jedis

Jedis 是 Redis 官方推出的一款面向 Java 的客户端,提供了很多接口供 Java 语言调用,可以在 Redis 官网下载,当然还有一些开源爱好者提供的客户端,如Jredis、SRP 等等,推荐使用 Jedis

1.3 Spring Data Redis

Spring-data-redis 是 spring 大家族的一部分,提供了在 srping 应用中通过简单的配置访问 redis 服务,对 reids 底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate 提供了 redis 各种操作、异常处理及序列化,支持发布订阅,并对 spring 3.1 cache 进行了实现


spring-data-redis 针对 jedis 提供了如下功能

  • 连接池自动管理,提供了一个高度封装的“RedisTemplate”类
  • 针对 jedis 客户端中大量 api 进行了归类封装,将同一类型操作封装为 operation接口
  • ValueOperations:简单 K-V 操作
  • SetOperations:set 类型数据操作
  • ZSetOperations:zset 类型数据操作
  • HashOperations:针对 map 类型的数据操作
  • ListOperations:针对 list 类型的数据操作

2. java-ssm框架使用redis存储数据环境准备

  • pom文件导入依赖
<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.2.RELEASE</version>
        </dependency>
  • 创建redis-config.properties文件
redis.host=192.168.25.120
redis.port=6379
redis.pass=
redis.database=0 
redis.maxIdle=300
redis.maxWait=3000
redis.testOnBorrow=true
  • 创建redis配置文件 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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath*:config/*.properties"/>
    <!-- redis 相关配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    </bean>
    <bean id="JedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"
          p:pool-config-ref="poolConfig"/>

    <!-- spring提供的模板对象 通过模板对象操作redis-->
    <bean id="redisTemplate"
          class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="JedisConnectionFactory"/>
    </bean>

</beans>

3. 举例-所有类型入门案例

3.1 值类型操作

package com.pyg.redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Set;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-02-01 17:07
 * @ classpath*      扫描所有的jar包,所有的配置文件
 * @ classpath       扫描当前项目下的编译路径
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring/applicationContext-redis.xml")
public class MyRedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void setValue(){
        redisTemplate.boundValueOps("name").set("ningning"); }
    @Test
    public void getValue(){
        String str = (String) redisTemplate.boundValueOps("name").get();
        System.out.println(str);
    }
    @Test
    public void deleteValue(){
        redisTemplate.delete("name");;
    }
}

3.2 Set类型操作

package com.pyg.redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Set;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-02-01 17:07
 * @ classpath*      扫描所有的jar包,所有的配置文件
 * @ classpath       扫描当前项目下的编译路径
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring/applicationContext-redis.xml")
public class MyRedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 存入值
     */
    @Test
    public void setValue() {
        redisTemplate.boundSetOps("nameset").add("曹操");
        redisTemplate.boundSetOps("nameset").add("刘备");
        redisTemplate.boundSetOps("nameset").add("孙权");
    }

    /**
     * 提取值
     */
    @Test
    public void getValue() {
        Set members = redisTemplate.boundSetOps("nameset").members();
        System.out.println(members);
    }

    /**
     * 删除集合中的某一个值
     */
    @Test
    public void deleteValue() {
        redisTemplate.boundSetOps("nameset").remove("孙权");
    }

    /**
     * 删除整个集合
     */
    @Test
    public void deleteAllValue() {
        redisTemplate.delete("nameset");
    }
}

3.3 List类型操作

package com.pyg.redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Set;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-02-01 17:07
 * @ classpath*      扫描所有的jar包,所有的配置文件
 * @ classpath       扫描当前项目下的编译路径
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring/applicationContext-redis.xml")
public class MyRedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 存入值
     */
    @Test
    public void setValue() {
        redisTemplate.boundSetOps("nameset").add("曹操");
        redisTemplate.boundSetOps("nameset").add("刘备");
        redisTemplate.boundSetOps("nameset").add("孙权");
    }

    /**
     * 右压栈:后添加的对象排在后边
     */
    @Test
    public void testSetValue1() {
        redisTemplate.boundListOps("namelist1").rightPush("刘备");
        redisTemplate.boundListOps("namelist1").rightPush("关羽");
        redisTemplate.boundListOps("namelist1").rightPush("张飞");
    }

    /**
     * 显示右压栈集合
     */
    @Test
    public void testGetValue1() {
        List list = redisTemplate.boundListOps("namelist1").range(0, 10);
        System.out.println(list);
        // 运行结果: [刘备, 关羽, 张飞]
    }


    /**
     * 左压栈:后添加的对象排在前边
     **/
    @Test
    public void testSetValue2() {
        redisTemplate.boundListOps("namelist2").leftPush("刘备");
        redisTemplate.boundListOps("namelist2").leftPush("关羽");
        redisTemplate.boundListOps("namelist2").leftPush("张飞");
    }

    /**
     * 显示左压栈集合
     */
    @Test
    public void testGetValue2() {
        List list = redisTemplate.boundListOps("namelist2").range(0, 10);
        System.out.println(list);
        // 运行结果 [张飞, 关羽, 刘备]
    }


    /**
     * 查询集合某个元素
     */
   

    @Test
    public void testSearchByIndex() {
        String s = (String) redisTemplate.boundListOps("namelist1").index(1);
        System.out.println(s);
    }

    /**
     * 移除集合某个元素
     */
    @Test
    public void testRemoveByIndex() {
        redisTemplate.boundListOps("namelist1").remove(1, "关羽");
    }


}

3.4 Hash类型操作

package com.pyg.redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.Set;

/**
 * @ Description
 * @ auther          宁宁小可爱
 * @ create          2020-02-01 17:07
 * @ classpath*      扫描所有的jar包,所有的配置文件
 * @ classpath       扫描当前项目下的编译路径
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring/applicationContext-redis.xml")
public class MyRedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testSetValue() {
        redisTemplate.boundHashOps("namehash").put("a", "唐僧");
        redisTemplate.boundHashOps("namehash").put("b", "悟空");
        redisTemplate.boundHashOps("namehash").put("c", "八戒");
        redisTemplate.boundHashOps("namehash").put("d", "沙僧");
    }

    /**
     * 提取所有的 KEY
     **/

    @Test
    public void testGetKeys() {
        Set s = redisTemplate.boundHashOps("namehash").keys();
        System.out.println(s);
        /** 运行结果: [a,b,c,d] **/
    }


    /**
     * 提取所有的值
     **/
    @Test

    public void testGetValues() {
        List values = redisTemplate.boundHashOps("namehash").values();
        System.out.println(values);
        /** 运行结果: [唐僧,悟空,八戒,沙僧]  **/
    }


    /**
     * 根据 KEY 提取值
     **/
    @Test

    public void testGetValueByKey() {
        Object object = redisTemplate.boundHashOps("namehash").get("b");
        System.out.println(object);
        /** 运行结果:悟空 **/
    }


    //根据 KEY 移除值
    @Test
    
    public void testRemoveValueByKey() {
        redisTemplate.boundHashOps("namehash").delete("c");
    }
}

4. 设置过期时间

redisTemplate.boundValueOps(phone).set(code);
        // 设置过期时间
        redisTemplate.boundValueOps(phone).expire(5, TimeUnit.MINUTES);