文档章节

spring整合redis

杨肥麻
 杨肥麻
发布于 2017/09/08 23:39
字数 676
阅读 17
收藏 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";

}

}

 

 

 

© 著作权归作者所有

共有 人打赏支持
杨肥麻
粉丝 1
博文 53
码字总数 30289
作品 0
深圳

暂无文章

Akka的Actor生命周期《Eight》译

Actor在创建时出现,然后在用户请求时停止。每当一个Actor停止时,它的所有孩子也会被递归停止。此行为极大地简化了资源清理,并有助于避免资源泄漏,例如由打开的套接字和文件引起的资源泄漏...

woshixin
6分钟前
0
0
Python 线程 条件锁 生产者消费者模型

创建多个生产者和消费者,并且加上条件锁,避免线程冲突 import threadingfrom threading import Threadfrom threading import Conditionimport timeimport randomc = Conditi...

阿豪boy
22分钟前
0
0
【七】组合Action

本章描述了常用定义Action的方法。 自定义action builders 我们在action一章已经看过如何声明一个action——有request parameter、无request parameter、有body parser等等。你可以在 asynch...

Landas
39分钟前
0
0
Spring Boot实战之基础回顾

本文作者: 吴伟祥 本文链接: https://wuweixiang.cn/2018/08/21/Spring-Boot实战之基础回顾/ 版权声明: 本博客所有文章除特别声明外均为原创,采用CC BY-NC-SA 4.0 许可协议。转载请在文章开...

吴伟祥
39分钟前
0
0
OAuth认证开发

提示: 以下测试是基于项目安装成功,初始化数据库(initial_db.ddl, oauth.ddl, initial_data.ddl)后的测试, 也可在页面上点击"client_details"菜单里进行测试 方式1:基于浏览器 (grant_type=...

舒文joven
48分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部