springboot---redis

摘要:
弹簧引导起动器数据redis<importjava.io.FileInputStream;//@RestController//@RequestMapping(“/ttt”)@Configuration//publicclassFileReids{//Jedisredis=newJedis(“localhost”);模板;

springboot---redis第1张

<!--redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

  redis: 
      database: 0 # Redis数据库索引(默认为0)
      host: 127.0.0.1
      port: 6379
      password: 123456  
      timeout: 0  # 连接超时时间(毫秒),0表示没有限制
      # cluster:
          # nodes: 192.168.211.134:7000,192.168.211.134:7001,192.168.211.134:7002
          # maxRedirects: 6
      pool:
          max-active: -1  # 连接池最大连接数(使用负值表示没有限制)
          min-idle: 0  # 连接池中的最小空闲连接
          max-idle: -1  # 连接池中的最大空闲连接
          max-wait: -1  # 连接池最大阻塞等待时间(使用负值表示没有限制)
package com.hcxy.car.spring.config.redis;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;


//@RestController
//@RequestMapping("/ttt")
@Configuration   //
public class FileReids {

//    Jedis redis = new Jedis("localhost");
    @Autowired
    @Qualifier("common_template")
    RedisTemplate<String, Object> template;

    @Autowired
    @Qualifier("file_template")
    RedisTemplate<String, Object> template1;

    //
//    @RequestMapping(value = "/aa", method = { RequestMethod.POST, RequestMethod.GET })
    public void move2redis(Object o1) {
        if(null == o1) return;
        String fileName = (String)o1; /*D:eclipsworksapce1 upgrade src main webapp  uploads33320180531110702FP_MCU_112.bin*/
        String key = fileName.substring(fileName.indexOf("upload")+"upload".length()+1).replace("\", ":");
        String name = key.substring(key.lastIndexOf(":")+1);//FP_MCU_112.bin
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
        if (fileName != null) {
            File file = new File(fileName);
            if (file.exists()) {
                byte[] buffer = new byte[5 * 1024 * 1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    int i = bis.read(buffer);
                    int j = 0;
                    while (i != -1) {
                        template1.opsForValue().set(key+":" + j++, buffer);
//                        out.write(buffer, 0, i);
                        System.out.println(i);
                        i = bis.read(buffer);
                    }
                    template.opsForValue().set(key+":total", j);
                } catch (Exception e) {
                }
            }
        }
        // return out.toByteArray();
    }

//    @RequestMapping(value = "/gg", method = { RequestMethod.POST, RequestMethod.GET })
    public void download(String s ,HttpServletResponse response) throws IOException {
        OutputStream os = response.getOutputStream();
        Object d = template.opsForValue().get(s+":total");
        if(null == d) return;
        for (int i = 0; i < Integer.valueOf(d.toString()); i++) {
            os.write((byte[]) template1.opsForValue().get(s+":" + i));//
        }
    }
    
    public boolean search(String s) {
        Object d =  template.opsForValue().get(s);
        return d == null ? false : true;
    }

     public void del2redis(String o1) {
         String[] s = o1.split(":"); //AVCN:X1:AU:20180619135343:FP_ARM_101.zip
         List<Package> l = pkService.findByDCV(s[0],s[1],s[2]);
         if(null == l || l.size() == 0) return;
         for(int i = 0; i < l.size(); i++) {
              String ss = s[0]+":"+s[1]+":"+s[2]+":"+l.get(i).getPackageVersion();

              Set<String> keys1 = template1.keys(ss + "*");

              template1.delete(keys1);
              Set<String> keys = template.keys(ss + "*");
              template.delete(keys);
}
}


}
package com.hcxy.car.spring.config.redis;

import java.io.Serializable;

public class Pruduct implements Serializable {

    private static final long serialVersionUID = 1L;
    int id;
    String name;
    String desc;

    public Pruduct() {
    }

    public Pruduct(int id, String name, String desc) {
        super();
        this.id = id;
        this.name = name;
        this.desc = desc;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Pruduct [id=" + id + ", name=" + name + ", desc=" + desc + "]";
    }
}
package com.hcxy.car.spring.config.redis;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class PruductDao {
    
    public Pruduct getPrud(int id) {
        System.out.println("sss");
        Pruduct p = new Pruduct(id, "name_"+id, "desc_"+id);
        return p;
    }

    public Pruduct getPrud2(int id) {
        System.out.println("www");
        Pruduct p = new Pruduct(id, "name_nocache"+id, "nocache");
        return p;
    }

}
package com.hcxy.car.spring.config.redis;

import java.lang.reflect.Method;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import redis.clients.jedis.JedisPoolConfig;

@Configuration  
@EnableAutoConfiguration  
public class RedisConfig extends CachingConfigurerSupport{  
  
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }    
    
    @Bean
    public RedisCacheManager cacheManager(RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }
    
    @Bean(name = "common_template")
    @Primary
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }
    
    @Bean(name = "file_template")
    public RedisTemplate redisTemplate1(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        
       /* Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);*/

        return template;
    }
    
    @Bean  
    @ConfigurationProperties(prefix="spring.redis")  
    public RedisConnectionFactory getConnectionFactory(){  
        JedisConnectionFactory factory = new JedisConnectionFactory();  
        JedisPoolConfig config = getRedisConfig();  
        factory.setPoolConfig(config);  
        return factory;  
    }  
    
    @Bean  
    @ConfigurationProperties(prefix="spring.redis")  
    public JedisPoolConfig getRedisConfig(){  
        JedisPoolConfig config = new JedisPoolConfig();  
        return config;  
    }  
}  
package com.hcxy.car.spring.config.redis;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/tt")
public class RedisTest {
    
    @Autowired
    RedisConnectionFactory factory;
    
    @Autowired    
    @Qualifier("common_template")
    RedisTemplate<String, Object> template;
    
    @RequestMapping(value = "/bb", method = { RequestMethod.POST, RequestMethod.GET })
    public void test(){
        System.out.println(this.getClass().getName());
    }
    
    @RequestMapping(value = "/aa", method = { RequestMethod.POST, RequestMethod.GET })
    public void testRedisTemplateList(){
    
        Pruduct prud  = new Pruduct(1, "ss", "100ml");
        Pruduct prud2  = new Pruduct(2, "ww", "200ml");
        template.opsForList().rightPush("pruduct1", prud);
        template.opsForList().rightPush("pruduct1", prud2);
        System.out.println("ee:"+template.opsForList().size("pruduct1"));
        
        List<Object> prodList = template.opsForList().range("pruduct1", 0,template.opsForList().size("pruduct1")-1);
        for(Object obj:prodList){
            System.out.println((Pruduct)obj);
        }
        
        Map<String,String> map = new HashMap<String, String>();
        map.put("value","code");
        map.put("key","keyValue");
        template.opsForHash().putAll("hashOps",map);
        
        Map<String,String> valueMap = new HashMap<String,String>();  
        valueMap.put("valueMap1","map1");  
        valueMap.put("valueMap2","map2");  
        valueMap.put("valueMap3","map3");  
        template.opsForValue().multiSet(valueMap);  
        
        template.opsForValue().set("name","tom");
        System.out.println(template.opsForValue().get("name"));  

        template.opsForValue().set("name:ii:oo:[p:iii","tom".getBytes());
        System.out.println("tom".getBytes());
        byte[] d = "tom".getBytes();
        for(byte i : d) {
            System.out.println(i);
        }
        System.out.println(template.opsForValue().get("name:ii:oo:[p:iii"));  
        
        template.opsForValue().set("key1", "value1");
        System.out.println(template.opsForValue().get("key1"));
        
        template.opsForValue().set("name:ii:oo:p:iii",3);
        System.out.println(template.opsForValue().get("name:ii:oo:p:iii"));  
        template.opsForValue().set("TBOX:300:20180522105038:123.rar:total","tom");
        Object dd =  template.opsForValue().get("TBOX:300:20180522105038:123.rar:total");
    }
    
    @RequestMapping(value = "/dcd", method = { RequestMethod.POST, RequestMethod.GET })
    public void testRedis(){
        RedisConnection conn = factory.getConnection();
        conn.set("hello".getBytes(), "world".getBytes());
        System.out.println(new String(conn.get("hello".getBytes())));
    }

}
package com.hcxy.car.spring.config.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    PruductDao pruductDao;
    
    /**
     * @param id
     * @return
     */
    @RequestMapping("/getPrud")
    @Cacheable("prudCache")
    public Pruduct getPrud(@RequestParam(required=true)String id){
        System.out.println(" ");
        return pruductDao.getPrud(Integer.parseInt(id));
    }
    /**
     * @param id
     * @return
     */
    @RequestMapping(value="/deletePrud")
    @CacheEvict("prudCache")
    public String deletePrud(@RequestParam(required=true)String id){
        return "SUCCESS";
    }
    
    /**
     * @param prud
     * @return
     */
    @RequestMapping("/savePrud")
    @CachePut(value="prudCache",key="#result.id +''")
    public Pruduct savePrud(Pruduct prud){
        return prud;
    }
    
    
    /**
     * @param id
     * @return
     */
    @RequestMapping("/getPrud2")
    @CachePut(value ="prudCache",unless="#result.desc.contains('nocache')")
    public Pruduct getPrud2(@RequestParam(required=true)String id){
        System.out.println(" ");
        Pruduct p = new Pruduct(Integer.parseInt(id), "name_nocache"+id, "nocache");
        return p;
    }
    

    
    @RequestMapping("/getPrud3")
    @Cacheable(value ="prudCache",key="#root.targetClass.getName() + #root.methodName + #id")
    public Pruduct getPrud3(@RequestParam(required=true)String id){
        System.out.println(" ");
        return pruductDao.getPrud(Integer.parseInt(id));
    }
    
    
    

}

免责声明:文章转载自《springboot---redis》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇sencha touch 监控页面中的超链接(a标签),使用系统浏览器打开链接PHP stdClass类 使用下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

oracle正则表达式函数 匹配

文章介绍了关于oracle正则函数的一些用法,包括匹配等,Oracle10g提供了在查询中使用正则表达的功能,它是通过各种支持正则表达式的函数在where子句中实现的。 ORACLE中的支持正则表达式的函数主要有下面四个: 1,REGEXP_LIKE :与LIKE的功能相似 2,REGEXP_INSTR :与INSTR的功能相似 3,REGEXP_SU...

windows端口占用处理方法

(1)输入命令:netstat -ano,列出所有端口的情况。在列表中我们观察被占用的端口,比如是8081,首先找到它。C:UsersAdministrator>netstat -ano活动连接协议 本地地址 外部地址 状态 PID ...................................TCP [::]:1036 [::]:0...

SpringBoot-配置MyBatis-yml方式

Druid的数据源配置:https://www.cnblogs.com/KuroNJQ/p/11171263.html 1.导入依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-sp...

雷林鹏分享:C# 可空类型(Nullable)

  C# 可空类型(Nullable)   C# 可空类型(Nullable)   C# 提供了一个特殊的数据类型,nullable 类型(可空类型),可空类型可以表示其基础值类型正常范围内的值,再加上一个 null 值。   例如,Nullable< Int32 >,读作"可空的 Int32",可以被赋值为 -2,147,483,648 到...

MongoDB副本集提高读写速率

一、提高副本集写的速率 1、通过设置Write Concern for Replica Sets¶ cfg = rs.conf()##cfg.settings.getLastErrorDefaults = { w: "majority", wtimeout: 5000 } cfg.settings.getLastErrorDefaults ={w:1}r...

Hibernate中批量保存数据

第一种方式 public void saveCus(final List<Cus> cuss) { this.getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session sessi...