springboot 整合redis 例子

首先是配置文件:

spring:
    redis:
        host: localhost
        password:  
        port: 6379
        pool:
          max-idle: 100
          min-idle: 1
          max-active: 1000
          max-wait: -1

创建RedisConfig配置类:

使用了spring自带的缓存,也可在这里配置Object类型的操作和其他类型的,这里就不演示了

@Configuration  
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
       CacheManager cacheManager = new RedisCacheManager(redisTemplate);
       return cacheManager;
    }
 
    //这里是使用string类型的操作
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
       RedisTemplate redisTemplate = new RedisTemplate();
       redisTemplate.setConnectionFactory(factory);
       return redisTemplate;
    }

}

service:

public interface RedisService {
	
	
	//add	
  public void set(String id, String name);  
  //select
  public String get(String id);  
  //update
  public void update(String id,String name);
  //delete
  public void delete(String id);
}

serviceImpl

@Service
public class RedisServiceImpl implements RedisService{

	@Resource
    private RedisTemplate redisTemplate; 	
	@Override
	public void set(String id, String name) {
		ValueOperations vo = redisTemplate.opsForValue();
        vo.set(id, name);
	}
 
 
	@Override
	public String get(String id) {
		ValueOperations vo=redisTemplate.opsForValue();
	   return vo.get(id);
	}
 
 
	@Override
	public void update(String id, String name) {
	   ValueOperations vo=redisTemplate.opsForValue();
	   vo.set(id, name);
	   
	}
 
 
	@Override
	public void delete(String id) {
	  ValueOperations vo=redisTemplate.opsForValue();
	  vo.getOperations().delete(id);
	}

}

controller:

@RestController
@RequestMapping("/redis")
public class RedisController {
	
	@Autowired
    RedisService redisService;
	
	 @RequestMapping(value = "setStr")
	    public String setStr(String key, String val){
	        try {
	            redisService.set(key, val);
	            return "success";
	        } catch (Exception e){
	            e.printStackTrace();
	            return "error";
	        }
	    }

	    /**
	     * 根据key查询Str缓存
	     * @param key
	     * @return
	     */
	    @RequestMapping(value = "getStr")
	    public String getStr(String key){
	        return redisService.get(key);
	    }


	    /**
	     * 根据key产出Str缓存
	     * @param key
	     * @return
	     */
	    @RequestMapping(value = "delStr")
	    public String delStr(String key){
	        try {
	            redisService.delete(key);
	            return "success";
	        } catch (Exception e){
	            return "error";
	        }
	    }
	 
}

然后浏览器直接访问就完事了

你可能感兴趣的:(redis)