一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - spring整合redis緩存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用

spring整合redis緩存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用

2020-09-15 14:10彩虹過后的羽翼 Java教程

本篇文章主要介紹了spring整合redis緩存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用,具有一定的參考價(jià)值,有興趣的可以了解一下。

maven項(xiàng)目中在pom.xml中依賴2個(gè)jar包,其他的spring的jar包省略:

?
1
2
3
4
5
6
7
8
9
10
<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>

spring-Redis.xml中的內(nèi)容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?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:mvc="http://www.springframework.org/schema/mvc"
  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/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
            http://www.springframework.org/schema/cache 
            http://www.springframework.org/schema/cache/spring-cache-4.2.xsd"> 
   
  <context:property-placeholder location="classpath:redis-config.properties" /> 
 
  <!-- 啟用緩存注解功能,這個(gè)是必須的,否則注解不會生效,另外,該注解一定要聲明在spring主配置文件中才會生效 -->
  <cache:annotation-driven cache-manager="cacheManager" /> 
   
   <!-- redis 相關(guān)配置 -->
   <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"/> 
  
   <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
     <property name="connectionFactory" ref="JedisConnectionFactory" /> 
   </bean
   
   <!-- spring自己的緩存管理器,這里定義了緩存位置名稱 ,即注解中的value -->
   <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"
     <property name="caches"
      <set
        <!-- 這里可以配置多個(gè)redis -->
        <!-- <bean class="com.cn.util.RedisCache"> 
           <property name="redisTemplate" ref="redisTemplate" /> 
           <property name="name" value="default"/> 
        </bean> -->
        <bean class="com.cn.util.RedisCache"
           <property name="redisTemplate" ref="redisTemplate" /> 
           <property name="name" value="common"/> 
           <!-- common名稱要在類或方法的注解中使用 -->
        </bean>
      </set
     </property
   </bean
   
</beans

redis-config.properties中的內(nèi)容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Redis settings
# server IP
redis.host=127.0.0.1
# server port
redis.port=6379
# server pass
redis.pass=
# use dbIndex
redis.database=0
# 控制一個(gè)pool最多有多少個(gè)狀態(tài)為idle(空閑的)的jedis實(shí)例
redis.maxIdle=300
# 表示當(dāng)borrow(引入)一個(gè)jedis實(shí)例時(shí),最大的等待時(shí)間,如果超過等待時(shí)間(毫秒),則直接拋出JedisConnectionException; 
redis.maxWait=3000
# 在borrow一個(gè)jedis實(shí)例時(shí),是否提前進(jìn)行validate操作;如果為true,則得到的jedis實(shí)例均是可用的 
redis.testOnBorrow=true

com.cn.util.RedisCache類中的內(nèi)容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package com.cn.util; 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
 
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
 
public class RedisCache implements Cache{
 
  private RedisTemplate<String, Object> redisTemplate; 
  private String name; 
  public RedisTemplate<String, Object> getRedisTemplate() {
    return redisTemplate; 
  }
    
  public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
    this.redisTemplate = redisTemplate; 
  }
    
  public void setName(String name) {
    this.name = name; 
  }
    
  @Override
  public String getName() {
    // TODO Auto-generated method stub 
    return this.name; 
  }
 
  @Override
  public Object getNativeCache() {
   // TODO Auto-generated method stub 
    return this.redisTemplate; 
  }
  
  @Override
  public ValueWrapper get(Object key) {
   // TODO Auto-generated method stub
   System.out.println("get key");
   final String keyf = key.toString();
   Object object = null;
   object = redisTemplate.execute(new RedisCallback<Object>() {
   public Object doInRedis(RedisConnection connection) 
         throws DataAccessException {
     byte[] key = keyf.getBytes();
     byte[] value = connection.get(key);
     if (value == null) {
       return null;
      }
     return toObject(value);
     }
    });
    return (object != null ? new SimpleValueWrapper(object) : null);
   }
  
   @Override
   public void put(Object key, Object value) {
    // TODO Auto-generated method stub
    System.out.println("put key");
    final String keyf = key.toString(); 
    final Object valuef = value; 
    final long liveTime = 86400
    redisTemplate.execute(new RedisCallback<Long>() { 
      public Long doInRedis(RedisConnection connection) 
          throws DataAccessException { 
        byte[] keyb = keyf.getBytes(); 
        byte[] valueb = toByteArray(valuef); 
        connection.set(keyb, valueb); 
        if (liveTime > 0) { 
          connection.expire(keyb, liveTime); 
         
        return 1L; 
       
     }); 
   }
 
   private byte[] toByteArray(Object obj) { 
     byte[] bytes = null
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     try
      ObjectOutputStream oos = new ObjectOutputStream(bos); 
      oos.writeObject(obj); 
      oos.flush(); 
      bytes = bos.toByteArray(); 
      oos.close(); 
      bos.close(); 
     }catch (IOException ex) { 
        ex.printStackTrace(); 
     
     return bytes; 
    
 
    private Object toObject(byte[] bytes) {
     Object obj = null
      try {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes); 
        ObjectInputStream ois = new ObjectInputStream(bis); 
        obj = ois.readObject(); 
        ois.close(); 
        bis.close(); 
      } catch (IOException ex) { 
        ex.printStackTrace(); 
      } catch (ClassNotFoundException ex) { 
        ex.printStackTrace(); 
      
      return obj; 
    }
  
    @Override
    public void evict(Object key) { 
     // TODO Auto-generated method stub 
     System.out.println("del key");
     final String keyf = key.toString(); 
     redisTemplate.execute(new RedisCallback<Long>() { 
     public Long doInRedis(RedisConnection connection) 
          throws DataAccessException { 
       return connection.del(keyf.getBytes()); 
      
     }); 
    }
  
    @Override
    public void clear() { 
      // TODO Auto-generated method stub 
      System.out.println("clear key");
      redisTemplate.execute(new RedisCallback<String>() { 
        public String doInRedis(RedisConnection connection) 
            throws DataAccessException { 
         connection.flushDb(); 
          return "ok"
        
      }); 
    }
 
    @Override
    public <T> T get(Object key, Class<T> type) {
      // TODO Auto-generated method stub
      return null;
    }
   
    @Override
    public ValueWrapper putIfAbsent(Object key, Object value) {
      // TODO Auto-generated method stub
      return null;
    }
 
}

到了這一步,大部分人會想在web.xml的啟動配置文件地方(context-param)加入了spring-redis.xml,讓項(xiàng)目啟動時(shí)加載這個(gè)配置文件吧,但是這樣啟動后注解不生效。

正確的做法是:web.xml中配置了servlet控制器:

?
1
2
3
4
5
6
7
8
9
10
<servlet>
 <servlet-name>SpringMVC</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring-mvc.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 <async-supported>true</async-supported>
</servlet>

在DispatcherServlet的初始化過程中,框架會在web應(yīng)用的 WEB-INF文件夾下尋找名為spring-mvc.xml的配置文件,如果不指定的話,默認(rèn)是applicationContext.xml

只需要在spring-mvc.xml文件中引入spring-redis配置文件即可,正如spring-redis.xml中的啟用注解說的:<cache:annotation-driven cache-manager="cacheManager" />注解一定要聲明在spring主配置文件中才會生效。

spring-mvc.xml內(nèi)容,省略了spring與spring MVC整合的那部分:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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:mvc="http://www.springframework.org/schema/mvc"
  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/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
  <!-- 自動掃描該包,使SpringMVC認(rèn)為包下用了@controller注解的類是控制器 -->
  <context:component-scan base-package="com.cn" /> 
   
  <!-- 引入同文件夾下的redis屬性配置文件 -->
  <import resource="spring-redis.xml"/>
   
</beans

在service的實(shí)現(xiàn)類中:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Service
public class UserServiceImpl implements UserService{
 
  @Autowired
  private UserBo userBo;
 
  @Cacheable(value="common",key="'id_'+#id")
  public User selectByPrimaryKey(Integer id) {
    return userBo.selectByPrimaryKey(id);
  }
   
  @CachePut(value="common",key="#user.getUserName()")
  public void insertSelective(User user) {
    userBo.insertSelective(user);
  }
 
  @CacheEvict(value="common",key="'id_'+#id")
  public void deleteByPrimaryKey(Integer id) {
    userBo.deleteByPrimaryKey(id);
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://blog.csdn.net/aqsunkai/article/details/51758900

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 91庥豆果冻天美精东蜜桃传媒 | 亚洲精品中文 | 91精品国产免费久久 | 国产香蕉视频在线观看 | 女人张开腿让男人桶视频免费大全 | 国内精品久久久久影院中国 | 天堂8在线天堂资源在线 | 99久久免费看国产精品 | 男人躁女人过程 | 富士av105| 插鸡小说 | 男人的天堂在线 | 免费观看大片毛片 | 国产成人亚洲精品91专区手机 | 男人在线网址 | 美国雪白人妖sarina | xxoosex久久久久久 | freese×video性欧美丝袜 | 手机看片日韩1024你懂的首页 | 小莹的性荡生活45章 | 午夜国产在线视频 | 激情视频激情小说 | 亚洲欧洲网站 | 星空无限传媒xk8027穆娜 | 小小水蜜桃视频高清在线播放 | 魔兽官方小说 | 国产亚洲欧美在线中文bt天堂网 | blackedvideos黑人| 3d动漫美女物被遭强视频 | 天堂中文在线观看 | 四虎国产| 日本女人www | 99精品全国免费7观看视频 | 久久精品一区二区三区资源网 | 国产精品日韩欧美在线 | 日韩成人在线免费视频 | 国产v在线播放 | 毛片一区二区三区提莫影院 | 亚洲国产区男人本色在线观看欧美 | 国内精品视频一区二区三区 | 午夜欧美精品久久久久久久久 |