spring整合redis
spring整合redis
杨肥麻 发表于3个月前
spring整合redis
  • 发表于 3个月前
  • 阅读 12
  • 收藏 1
  • 点赞 0
  • 评论 0

腾讯云 新注册用户 域名抢购1元起>>>   

1.安装redis缓存服务器

到https://github.com/dmajkic/redis/downloads网站上下载

redis-2.4.5-win32-win64.zip 包含32位和64位

2.下载后解压(打开缓存服务器)

然后cmd执行 redis-server.exe redis.conf

 

Spring整合redis

1.可以用maven下载

jedis-2.1.0.jar

spring-data-redis-1.0.2.RELEASE.jar

Spring项目加入这两个jar包

2.redis配置文件redis.properties

#redis setting  

redis.host=127.0.0.1

redis.port=6379

redis.password=

redis.maxIdle=100

redis.maxActive=300

redis.maxWait=1000

redis.testOnBorrow=true

redis.timeout=100000

fep.local.cache.capacity =10000

3.spring-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:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="

     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd

     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd

     http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.2.xsd"

    default-autowire="byName" default-lazy-init="true">

 

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">

        <property name="maxIdle" value="${redis.maxIdle}" />

        <property name="maxWait" value="${redis.maxWait}" />

        <property name="testOnBorrow" value="${redis.testOnBorrow}" />

    </bean>

    <!-- redis服务器中心 -->

    <bean id="connectionFactory"

        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">

        <property name="poolConfig" ref="poolConfig" />

        <property name="port" value="${redis.port}" />

        <property name="hostName" value="${redis.host}" />

        <property name="password" value="${redis.password}" />

        <property name="timeout" value="${redis.timeout}"></property>

    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">

        <property name="connectionFactory" ref="connectionFactory" />

        <property name="keySerializer">

            <bean

                class="org.springframework.data.redis.serializer.StringRedisSerializer" />

        </property>

        <property name="valueSerializer">

            <bean

                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />

        </property>

    </bean>

 

    <bean id="redisUtil" class="com.redis.RedisUtil">

        <property name="redisTemplate" ref="redisTemplate" />

    </bean>

 

</beans>

4.applicationContext.xml

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

 <import resource="classpath:redis-config.xml"/>

5.缓存类RedisUtil.Java

package com.redis;

 

import java.io.Serializable;  

import java.util.Set;  

import java.util.concurrent.TimeUnit;  

 

import org.springframework.data.redis.core.RedisTemplate;  

import org.springframework.data.redis.core.ValueOperations;  

 

public class RedisUtil {

 

    private RedisTemplate<Serializable, Object> redisTemplate;

 

    /**

     * 批量删除对应的value

     *

     * @param keys

     */

    public void remove(final String... keys) {

        for (String key : keys) {

            remove(key);

        }

    }

 

    /**

     * 批量删除key

     *

     * @param pattern

     */

    public void removePattern(final String pattern) {

        Set<Serializable> keys = redisTemplate.keys(pattern);

        if (keys.size() > 0)

            redisTemplate.delete(keys);

    }

 

    /**

     * 删除对应的value

     *

     * @param key

     */

    public void remove(final String key) {

        if (exists(key)) {

            redisTemplate.delete(key);

        }

    }

 

    /**

     * 判断缓存中是否有对应的value

     *

     * @param key

     * @return

     */

    public boolean exists(final String key) {

        return redisTemplate.hasKey(key);

    }

 

    /**

     * 读取缓存

     *

     * @param key

     * @return

     */

    public Object get(final String key) {

        Object result = null;

        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();

        result = operations.get(key);

        return result;

    }

 

    /**

     * 写入缓存

     *

     * @param key

     * @param value

     * @return

     */

    public boolean set(final String key, Object value) {

        boolean result = false;

        try {

            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();

            operations.set(key, value);

            result = true;

        } catch (Exception e) {

            //logger.error("set cache error", e);

        }

        return result;

    }

 

    /**

     * 写入缓存

     *

     * @param key

     * @param value

     * @return

     */

    public boolean set(final String key, Object value, Long expireTime) {

        boolean result = false;

        try {

            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();

            operations.set(key, value);

            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);

            result = true;

        } catch (Exception e) {

            //logger.error("set cache error", e);

        }

        return result;

    }

    

    public long increment(final String key , long delta){

         return redisTemplate.opsForValue().increment(key, delta);

    }

 

    public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {

        this.redisTemplate = redisTemplate;

    }

}

6.Controller访问

package com.controller;

 

import java.util.HashMap;

import java.util.Map;

 

import javax.servlet.http.HttpServletRequest;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

 

 

import com.model.User;

import com.redis.RedisUtil;

import com.service.LoginService;

 

@Controller

public class LoginController{

 

@Autowired

private LoginService  loginService;

 

@Autowired

private RedisUtil redisUtil;  //记得注入

 

@RequestMapping(value = "/queryUser.do")

public String queryUser(@RequestParam String hello,

HttpServletRequest request){

 User user = new User();

 Map<String, String> map = new HashMap<String, String>();

 Map<String, String> mapu = new HashMap<String, String>();

 if (redisUtil.exists("map")) {

     mapu = (Map)redisUtil.get("map");

 }

 if(mapu==null){

 user = loginService.queryUser(36);

 map.put("username", user.getUsername());

 map.put("password", user.getPassword());

 redisUtil.set("map", map);

 }

 return "user_list";

}

 

@RequestMapping(value = "/addUser.do")

public String addUser(@RequestParam String username, String password,

HttpServletRequest request){

User user=new User();

user.setUsername(username);

user.setPassword(password);

loginService.insertUser(user);

 return "user_list";

}

}

 

 

 

共有 人打赏支持
粉丝 2
博文 42
码字总数 18644
×
杨肥麻
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: