springboot---redis
阿新 • • 發佈:2018-06-19
base util nts pin cache str stp index style
<!--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: 123456timeout: 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 \ upload\s\333\20180531110702\FP_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; } }
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