spring+redis

5 篇文章 0 订阅
配置redis缓存

1.jar的版本选择:避免在配置中出现不兼容,推荐版本:
jedis-2.9.0.jar
spring-data-redis-1.6.2.RELEASE.jar
spring-data-commons-1.8.6.RELEASE.jar
这是配置redis的核心包 也可以使用其他的版本

2.配置环境的选择:避免出现spring+redis的不兼容:
推荐版本:spring4.2+redis2.9+jdk1.8

3.redis参数选择:redis.properties
#ip地址  
redis.host=127.0.0.1  
#端口号  
redis.port=6379  
#如果有密码  
redis.password=123456
#客户端超时时间单位是毫秒 默认是2000  
redis.timeout=10000  
#最大空闲数  
redis.maxIdle=300  
#连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal  
#redis.maxActive=600  
#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性  
redis.maxTotal=1000  
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。  
redis.maxWaitMillis=1000  
#连接的最小空闲时间 默认1800000毫秒(30分钟)  
redis.minEvictableIdleTimeMillis=300000  
#每次释放连接的最大数目,默认3  
redis.numTestsPerEvictionRun=1024  
#逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1  
redis.timeBetweenEvictionRunsMillis=30000  
#是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个  
redis.testOnBorrow=true  
#在空闲时检查有效性, 默认false  
redis.testWhileIdle=true 
#选择第几个库
redis.database=2



4.spring+redis的配置环境:redisConfig.xml 我的redis的配置 可借鉴


<?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:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx" 
       xmlns:task="http://www.springframework.org/schema/task" 
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-
context-4.2.xsd 
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd  
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-
4.2.xsd
         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-
4.2.xsd">
    <!-- * 优势:简单直观,效率高
         * 劣势:系统中只能用Redis一种缓存了 
                               使用redis内置CacheManager-->
         
<!-- jedis 配置  连接池配置-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
     <!-- #最大空闲数   -->
<property name="maxIdle" value="${redis.maxIdle}" />
<!-- #控制一个pool可分配多少个jedis实例 -->
<property name="maxTotal" value="${redis.maxTotal}" />  
<!-- #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。 -->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<!-- #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 -->
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
 
<!-- redis服务器中心  连接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}" />
<!-- #客户端超时时间单位是毫秒 默认是2000 -->
<property name="timeout" value="${redis.timeout}"></property>
<!-- #选择redis第几个库 -->
<property name="database" value="${redis.database}" />
</bean>
 
 <!-- redis template,被后面的RedisCacheManager或RedisCache引用 --> 
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
  <!--开启事务  -->  
          <property name="enableTransactionSupport" value="true"/>
          <!--value,key值 的序列化  Redis缓存对象乱码处理-->
  <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
          </property>
         <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
         </property>
         <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
         </property>
         <property name="hashValueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
         </property>
         <property name="stringSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
         </property>
</bean>
 
<!-- 配置缓存 -->
<!-- 允许基于注解的使用,proxy-target-class默认为false,即使用JDK Proxy机制,如设置为true则基于CGLIB动态生
成代理类 --> 
<cache:annotation-driven cache-manager="cacheManager" />
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
     <property name="usePrefix" value="true" /> 
         <property name="defaultExpiration" value="3600"/>
     <constructor-arg ref="redisTemplate" />
     <!-- 下面列表每一项对应一个Cache对象的名字,也就是@Cacheable的value指向的值-->  
         <constructor-arg>  
          <list>  
             <value>default</value><!-- 缓存名,在注解中用value引用 -->  
             <value>user</value><!-- 可以配置多个缓存,以实现不同的超时策略 -->  
          </list>  
        </constructor-arg>  
        <!-- 用expires属性分别配置其超时时间,缺省则使用defaultExpiration,单位均为秒 -->  
        <property name="expires">  
          <map>  
              <entry key="user" value="60"/><!-- value="0"此缓存永不超时,即使Redis重启也不会丢失哟 -->  
          </map>  
        </property> 
</bean>
</beans>




我的spring配置:springContext.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:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx" 
       xmlns:task="http://www.springframework.org/schema/task" 
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-
context-4.2.xsd 
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd  
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-
4.2.xsd
           http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">

<!-- 配置自动识别注解 -->
    <context:component-scan base-package="com.dome" >
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- <task:annotation-driven/> -->
    <task:annotation-driven executor="asyncExecutor" scheduler="scheduler"/>
  <task:executor id="asyncExecutor" pool-size="100-1000" queue-capacity="10000" rejection-


policy="CALLER_RUNS"/>
  <task:scheduler id="scheduler" pool-size="100" />

    <!--加载数据库配置文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
           <list>
              <!-- 加载数据库连接设置 -->
  <value>classpath:config/database.properties</value>
  <!-- <value>classpath:config/database.properties</value> -->
  <!-- 加载redis连接设置 -->
  <value>classpath:config/redis.properties</value>
          </list>
      </property>
    </bean>
    
<!-- 数据中心连接 -->   
<import resource="datasource-sqlserverTwo.xml" /> 
<!-- redis 缓存设置 -->
<import resource="redisConfig.xml" />
<!-- spring ehcache+redis 缓存设置 2个以上缓存组合使用 效率略低于redis -->
<!-- <import resource="spring-cache.xml" /> -->

<!-- 解决使用@ResponseBody 的中文乱码。 --> 
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <!-- JSON解析对象 -->
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
                <property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
                </bean>  
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
                    <property name="supportedMediaTypes">  
                        <list>  
                            <value>text/plain;charset=UTF-8</value>  
                        </list>  
                    </property>  
                </bean>  
            </list>  
        </property>
         <!-- 日期格式转换 -->
    <property name="webBindingInitializer">    
        <bean class="com.dome.filter.DateConverterFilter" />    
    </property>    
    </bean>
 
  <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">  
  <!-- 验证码  kaptcha-->
        <property name="config">  
            <bean class="com.google.code.kaptcha.util.Config">  
                <constructor-arg>  
                    <props>  
                        <prop key="kaptcha.border">yes</prop>  
                        <prop key="kaptcha.border.color">105,179,90</prop>  
                        <prop key="kaptcha.textproducer.font.color">blue</prop>  
                        <prop key="kaptcha.image.width">125</prop>  
                        <prop key="kaptcha.image.height">45</prop>  
                        <prop key="kaptcha.textproducer.font.size">45</prop>  
                        <prop key="kaptcha.session.key">kaptchaRemote</prop>  
                        <prop key="kaptcha.textproducer.char.length">4</prop>  
                        <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>  
                    </props>  
                </constructor-arg>  
            </bean>  
        </property>  
    </bean>  
</beans>


5.配置好redis就可以使用啦 不用写其他的实现类或者监听的 我看见很多楼主都写了什么实现类,监听来实现redis的调用,完
全不是基于注解的  这里配置好就可以去注解调用啦   redis的实现也是基于spring aop上的 所有redis的实现也是基于代理模式 redis 和事物处理差不多,都是放在service层的  执行sql语句时,都是先检索redis缓存 没有缓存数据 在操作数据库


6.service层的代码:其他无需有变动 在service 层 注解 redis就生效啦
package com.dome.service.user.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.dome.bean.user.User;
import com.dome.dao.source2.user.UserMapper;
import com.dome.service.user.UserService;
@Service
public class UserServiceImpl implements UserService {
/**
* userService

* 缓存机制说明:所有的查询结果都放进了缓存,也就是把MySQL查询的结果放到了redis中去,
* 然后第二次发起该条查询时就可以从redis中去读取查询的结果,从而不与MySQL交互,从而达到优化的效果,
* redis的查询速度之于MySQL的查询速度相当于 内存读写速度/硬盘读写速度
* @Cacheable("a")注解的意义就是把该方法的查询结果放到redis中去,
* 下一次再发起查询就去redis中去取,存在redis中的数据的key就是a;
* @CacheEvict(value={"a","b"},allEntries=true)
* 的意思就是执行该方法后要清除redis中key名称为a,b的数据;
* key 命名规范
* 当前被调用的方法使用的Cache:#root.caches[0].name
* 当前方法名#root.methodName  当前方法#root.method.name 当前被调用的对象#root.target 当前被调用的对象的

class#root.targetClass
* 当前方法参数组成的数组#root.args[0] 当前被调用的方法使用的Cache#root.caches[0].name */
@Autowired
private UserMapper userMapper;
@Cacheable(value="default",key="#root.caches[0].name + '_' +#root.targetClass+ '_' +#root.methodName")
@Override
public User selectOne() {
return userMapper.selectOne();
}
}

7.spring+redis的集成配置就完成啦  你的是spring+mybatis+springmvc+redis 还是spring + hibernate+springmvc+redis 还是最新的分布式 其他配置就需要自己完善  spring+redis的配置就这些

配置redis的集成注意点:
1.
jedis-2.9.0.jar
spring-data-redis-1.6.2.RELEASE.jar
spring-data-commons-1.8.6.RELEASE.jar
三个依赖包兼容冲突上;
2.@Cacheable是spring4.1以上提供的注解
3.spring与jedis的依赖兼容上
4.使用redis或者spring的Cache+redis都需要声明<cache:annotation-driven cache-manager="cacheManager" />缓存开启 及调用哪个缓存 我这类调用的是redis的cacheManager
5.开启啦redis缓存其他缓存就不能运行啦 否则redis无法生效 很多人都出现说@Cacheable都注解啦,为什么没有效果的原因。比如你用啦redis缓存,那你的把mybatis自身的缓存关闭或则其他的缓存关闭,这是redis的劣势所在
6.redis的实现是基于代理模式的,所以在一个service方法里调用另外一个加拉redis缓存的方法 被调用的方法redis缓存肯定不会
生效的 为什么  可以去看看aop代理模式
7.@Cacheable(value="default",key="") 注解里的value必须有值 我这类设置啦缓存放置的地方 配置里的
<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
     <property name="usePrefix" value="true" /> 
         <property name="defaultExpiration" value="3600"/>
     <constructor-arg ref="redisTemplate" />
     <!-- 下面列表每一项对应一个Cache对象的名字,也就是@Cacheable的value指向的值-->  
         <constructor-arg>  
          <list>  
             <value>default</value><!-- 缓存名,在注解中用value引用 -->  
             <value>user</value><!-- 可以配置多个缓存,以实现不同的超时策略 -->  
          </list>  
        </constructor-arg>  
        <!-- 用expires属性分别配置其超时时间,缺省则使用defaultExpiration,单位均为秒 -->  
        <property name="expires">  
          <map>  
              <entry key="user" value="60"/><!-- value="0"此缓存永不超时,即使Redis重启也不会丢失哟 -->  
          </map>  
        </property> 
</bean>
其中
<list>  
        <value>default</value><!-- 缓存名,在注解中用value引用 -->  
         <value>user</value><!-- 可以配置多个缓存,以实现不同的超时策略 -->  
</list> 
就是我这里设置的 key随便你写 你的保证他的唯一性 redis是根据它来查找缓存的
8.实体类必须实现序列化:implements Serializable 序列化就是把对象进行流化进行内存,磁盘存储 而redis 必须要把实体类序列化才能生效

如果这几点 你不知道 集合redis出错 很正常
 
本人项目demo连接下载:https://download.csdn.net/download/rainjm/10391182
内含:spring4.2+jdk1.8+mybatis+redis+springmvc+tomcat8.5框架的集成及配置
内含分页监听,请求拦截,登录拦截,字符串编码等全局处理 可借鉴
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现搜索提示词可以通过以下步骤: 1. 在Spring中配置Redis连接池和RedisTemplate。 2. 创建一个搜索提示词的数据结构,可以使用有序集合(Sorted Set)。 3. 当用户每次输入一个字符时,从Redis中获取以该字符为前缀的搜索提示词,可以使用ZREVRANGEBYLEX命令。 4. 将获取到的搜索提示词返回给用户。 以下是示例代码: 1. 在Spring中配置Redis连接池和RedisTemplate。 ```java @Configuration public class RedisConfig { @Bean public LettuceConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("localhost", 6379); return new LettuceConnectionFactory(config); } @Bean public RedisTemplate<String, String> redisTemplate() { RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory()); redisTemplate.setDefaultSerializer(new StringRedisSerializer()); return redisTemplate; } } ``` 2. 创建一个搜索提示词的数据结构,可以使用有序集合(Sorted Set)。 ```java public class SearchSuggestion { private RedisTemplate<String, String> redisTemplate; public SearchSuggestion(RedisTemplate<String, String> redisTemplate) { this.redisTemplate = redisTemplate; } public void add(String keyword, double score) { redisTemplate.opsForZSet().add("search:keywords", keyword, score); } public List<String> suggest(String prefix) { Set<String> suggestions = redisTemplate.opsForZSet().reverseRangeByLex("search:keywords", new RedisZSetCommands.Range().gte(prefix).lte(prefix + Character.MAX_VALUE)); return new ArrayList<>(suggestions); } } ``` 3. 当用户每次输入一个字符时,从Redis中获取以该字符为前缀的搜索提示词,可以使用ZREVRANGEBYLEX命令。 ```java @RestController public class SearchController { private SearchSuggestion searchSuggestion; @Autowired public SearchController(RedisTemplate<String, String> redisTemplate) { this.searchSuggestion = new SearchSuggestion(redisTemplate); } @GetMapping("/suggest") public List<String> suggest(@RequestParam String prefix) { return searchSuggestion.suggest(prefix); } } ``` 4. 将获取到的搜索提示词返回给用户。 ```html <!DOCTYPE html> <html> <head> <title>Search Suggestion</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <input v-model="prefix" @input="suggest"> <ul> <li v-for="keyword in keywords">{{ keyword }}</li> </ul> </div> <script> new Vue({ el: '#app', data: { prefix: '', keywords: [] }, methods: { suggest: function () { axios.get('/suggest', {params: {prefix: this.prefix}}) .then(response => this.keywords = response.data) .catch(error => console.log(error)); } } }); </script> </body> </html> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ctrl+C+V程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值