spring整合springmvcc 能整合ssdb吗

Redis安装及Ubuntu 14.04下搭建ssdb主从环境_服务器应用_Linux公社-Linux系统门户网站
你好,游客
Redis安装及Ubuntu 14.04下搭建ssdb主从环境
来源:oschina.net &
作者:青涩年华
在工作中接触到了redis,Redis是一个非常高效的key-value的数据库,在项目中广泛使用,但是redis很明显的缺点是对于内存的处理,在项目上线之初,必须对内存规划合理,否则很容易出现内存爆了的现象,一般较合理的内存大小为电脑物理内存的3/5。
redis提供了多种数据类型,我经常使用的为string 、hash、list、set、sorted set,基本能满足项目对于数据类型的要求。我们使用的是redis的Java客户端,提供了一系列针对redis命令对应的api。redis的持久化提供了多种策略,但我们没有去做持久化,自己研究了下,AOF方式感觉是最可靠的,原理和mysql的二进制日志很类似,也是将操作信息记录下来写到文件,从服务器去读取日志并执行操作。
在平常内网开发中可能经常需要调整数据存储细节,所以如果之前的数据依然驻留在内存中,会导致很多功能无法正常运行,所以在调整细节之后,需要对redis数据库flushdb操作。
redis与ssdb在某些场景很适合使用,比如某些数据在数据库中只能残留2分钟,类似YY频道T人,固定几分钟后才能进来,就可以使用setex key seconds value命令,之后判断是否过期可以通过exists key 命令。
redis常用命令网站:http://redis.readthedocs.org/en/latest/&
涵盖了redis的命令及demo.
在搭ssdb前说redis,因为ssdb很好的兼容了redis的api。是redis的很好替代品。
ssdb相对于redis来说有很多优点:是redis数据库的100倍容量,可以存储几十亿的数据量。相对redis来说,占用内存很少。所以自己也去下载了ssdb,以下是ssdb搭建的过程。
14.04下Redis安装及简单测试
Redis集群明细文档
Ubuntu 12.10下安装Redis(图文详解)+ Jedis连接Redis
Redis系列-安装部署维护篇
6.3安装Redis
Redis配置文件redis.conf 详解
环境:Ubuntu 14.04
虚拟机A: 192.168.1.251
虚拟机B: 192.168.1.252
网关: 192.168.1.1
我的两台虚拟机是分别装在不同的物理机上,但都采用的是桥接方式,ip地址都是在同一个ip段。
在两台虚拟机下分别都在线安装下ssdb.
wget --no-check-certificate https://github.com/ideawu/ssdb/archive/master.zip
unzip master
cd ssdb-master
sudo make install
这些在ssdb官网都能找到,http://www.ideawu.com/ssdb/zh_cn/。
ssdb主从搭建其实非常之简单,你只需要在两台虚拟机ssdb安装目录下找到ssdb.conf.
sudo vi ssdb.conf
修改server 下的ip为虚拟机默认的IP地址。
ip:192.168.1.251
port:8888&
//我端口没改,用默认
ip:192.168.1.252
这是最基本的配置。
现在只要在A的基础上对于ssdb.conf下配置:
replication:
# to identify a master even if it moved(ip, port changed)
# if set to empty or not defined, ip:port will be used.
# sync|mirror, default is sync
type: sync
ip: 192.168.1.252
port: 8888
注意:在以上的配置过程中,千万不要用空格键,使用tab.
现在可以启动ssdb了。
./ssdb-server ssdb.conf
之后就可以使用ssdb提供的命令行工具来操作了。
虚拟机A:& & ./ssdb-cli -h 192.168.1.251 -p 8888
虚拟机B:& & ./ssdb-cli -h 192.168.1.252 -p 8888
Redis 的详细介绍:Redis 的下载地址:
更多Ubuntu相关信息见 专题页面
本文永久更新链接地址:
相关资讯 & & &
& (09月30日)
& (08月15日)
& (10月11日)
& (09月16日)
& (06月14日)
   同意评论声明
   发表
尊重网上道德,遵守中华人民共和国的各项有关法律法规
承担一切因您的行为而直接或间接导致的民事或刑事法律责任
本站管理人员有权保留或删除其管辖留言中的任意内容
本站有权在网站内转载或引用您的评论
参与本评论即表明您已经阅读并接受上述条款他的最新文章
他的热门文章
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)In this article I want to examine an example of Spring MVC + Hibernate + Maven usage. This set of technology implies basic knowledge of the domain area. So I will try to explain all essential moments in detail. The other things which are out of topic, will be provided with links to more detail sources. In the end of the post I will publish a link to GitHub.
Now you can try a new tutorial on the same theme but with .
Creation of the sample web application, based on Spring MVC, Hibernate, Maven. Interface will be HTML-based. The application will support all CRUD operations: create, read, update, delete. As usually I will use MySQL as a database. The application will be work with football clubs entities, so be ready that the tutorial will be in a sport direction.
Preparations
I will need one table in the database, and here is a code for its creation:
CREATE TABLE `teams` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`rating` int(6) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
This table will be represented in the application with the class:
@Table(name=&teams&)
public class Team {
@GeneratedValue
public Integer getId() {
public void setId(Integer id) {
public String getName() {
public void setName(String name) {
this.name =
public Integer getRating() {
public void setRating(Integer rating) {
this.rating =
Then I need to create a new Maven Web Project in IDE (I use Eclipse). I will omit the details of creation, you can read about this in one of my articles about . Here is a link to the
The first important stop is WebAppConfig.java file, so let’s consider:
@Configuration
@ComponentScan(&com.sprhib&)
@EnableWebMvc
@EnableTransactionManagement
@PropertySource(&classpath:application.properties&)
public class WebAppConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = &db.driver&;
private static final String PROPERTY_NAME_DATABASE_PASSWORD = &db.password&;
private static final String PROPERTY_NAME_DATABASE_URL = &db.url&;
private static final String PROPERTY_NAME_DATABASE_USERNAME = &db.username&;
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = &hibernate.dialect&;
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = &hibernate.show_sql&;
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = &entitymanager.packages.to.scan&;
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataS
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryB
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionM
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix(&/WEB-INF/pages/&);
resolver.setSuffix(&.jsp&);
resolver.setViewClass(JstlView.class);
At the start of the file you can see @EnableTransactionManagement, it enables Spring’s annotation-driven transaction management capability. Annotation @PropertySource(“classpath:application.properties”) – plugs in property file which located in the resource folder.
Pay your attention on three beans: transactionManager, sessionFactory, dataSource. These beans provide transaction management. For more information read my article about .
#DB properties:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/hibnatedb
db.username=hibuser
db.password=root
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=com.sprhib.model
Thats all what is related to project preparation. Further I’m going to show you DAO and service layers.
DAO & Service layers
Here are DAOs and Services interfaces and implementations:
public interface TeamDAO {
public void addTeam(Team team);
public void updateTeam(Team team);
public Team getTeam(int id);
public void deleteTeam(int id);
public List&Team& getTeams();
Implementation of the DAO interface:
@Repository
public class TeamDAOImpl implements TeamDAO {
@Autowired
private SessionFactory sessionF
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
public void addTeam(Team team) {
getCurrentSession().save(team);
public void updateTeam(Team team) {
Team teamToUpdate = getTeam(team.getId());
teamToUpdate.setName(team.getName());
teamToUpdate.setRating(team.getRating());
getCurrentSession().update(teamToUpdate);
public Team getTeam(int id) {
Team team = (Team) getCurrentSession().get(Team.class, id);
public void deleteTeam(int id) {
Team team = getTeam(id);
if (team != null)
getCurrentSession().delete(team);
@SuppressWarnings(&unchecked&)
public List&Team& getTeams() {
return getCurrentSession().createQuery(&from Team&).list();
Annotation @Repository Indicates that an annotated class is a “DAO”.
public interface TeamService {
public void addTeam(Team team);
public void updateTeam(Team team);
public Team getTeam(int id);
public void deleteTeam(int id);
public List&Team& getTeams();
Implementation of the Service interface:
@Transactional
public class TeamServiceImpl implements TeamService {
@Autowired
private TeamDAO teamDAO;
public void addTeam(Team team) {
teamDAO.addTeam(team);
public void updateTeam(Team team) {
teamDAO.updateTeam(team);
public Team getTeam(int id) {
return teamDAO.getTeam(id);
public void deleteTeam(int id) {
teamDAO.deleteTeam(id);
public List&Team& getTeams() {
return teamDAO.getTeams();
Annotation @Service indicates that an annotated class is a “Service”. Annotation @Transactional describes transaction attributes on a method or class.
Controllers & JSPs
Since I’m going to cover all CRUD operations, this chapter will be a little bit long. I will start from the base controller, it resposible for the Home page:
@Controller
public class LinkController {
@RequestMapping(value=&/&)
public ModelAndView mainPage() {
return new ModelAndView(&home&);
@RequestMapping(value=&/index&)
public ModelAndView indexPage() {
return new ModelAndView(&home&);
It is simple enough, and here its JSP file:
&h1&Home page&/h1&
${message}&br/&
&a href=&${pageContext.request.contextPath}/team/add.html&&Add new team&/a&&br/&
&a href=&${pageContext.request.contextPath}/team/list.html&&Team list&/a&&br/&
And here is a monster-class, the main controller of the application:
@Controller
public class TeamController {
@Autowired
private TeamService teamS
@RequestMapping(value=&/team/add&)
public ModelAndView addTeamPage() {
ModelAndView modelAndView = new ModelAndView(&add-team-form&);
modelAndView.addObject(&team&, new Team());
return modelAndV
@RequestMapping(value=&/team/add/process&)
public ModelAndView addingTeam(@ModelAttribute Team team) {
ModelAndView modelAndView = new ModelAndView(&home&);
teamService.addTeam(team);
String message = &Team was successfully added.&;
modelAndView.addObject(&message&, message);
return modelAndV
@RequestMapping(value=&/team/list&)
public ModelAndView listOfTeams() {
ModelAndView modelAndView = new ModelAndView(&list-of-teams&);
List&Team& teams = teamService.getTeams();
modelAndView.addObject(&teams&, teams);
return modelAndV
@RequestMapping(value=&/team/edit/{id}&, method=RequestMethod.GET)
public ModelAndView editTeamPage(@PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView(&edit-team-form&);
Team team = teamService.getTeam(id);
modelAndView.addObject(&team&,team);
return modelAndV
@RequestMapping(value=&/team/edit/{id}&, method=RequestMethod.POST)
public ModelAndView edditingTeam(@ModelAttribute Team team, @PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView(&home&);
teamService.updateTeam(team);
String message = &Team was successfully edited.&;
modelAndView.addObject(&message&, message);
return modelAndV
@RequestMapping(value=&/team/delete/{id}&, method=RequestMethod.GET)
public ModelAndView deleteTeam(@PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView(&home&);
teamService.deleteTeam(id);
String message = &Team was successfully deleted.&;
modelAndView.addObject(&message&, message);
return modelAndV
Almost all methods and request mappings are clear. But I want to underline that @RequestMapping for the editTeamPage() and edditingTeam() methods, contains different valuse for the method attribute.
And now it’s time to see JSPs for these mappings:
“Add new team” page:
&h1&Add team page&/h1&
&p&Here you can add a new team.&/p&
&form:form method=&POST& commandName=&team& action=&${pageContext.request.contextPath}/team/add/process.html&&
&td&Name:&/td&
&td&&form:input path=&name& /&&/td&
&td&Rating:&/td&
&td&&form:input path=&rating& /&&/td&
&td&&input type=&submit& value=&Add& /&&/td&
&/form:form&
&p&&a href=&${pageContext.request.contextPath}/index.html&&Home page&/a&&/p&
“List of teams” page:
&h1&List of teams&/h1&
&p&Here you can see the list of the teams, edit them, remove or update.&/p&
&table border=&1px& cellpadding=&0& cellspacing=&0& &
&th width=&10%&&id&/th&&th width=&15%&&name&/th&&th width=&10%&&rating&/th&&th width=&10%&&actions&/th&
&c:forEach var=&team& items=&${teams}&&
&td&${team.id}&/td&
&td&${team.name}&/td&
&td&${team.rating}&/td&
&a href=&${pageContext.request.contextPath}/team/edit/${team.id}.html&&Edit&/a&&br/&
&a href=&${pageContext.request.contextPath}/team/delete/${team.id}.html&&Delete&/a&&br/&
&/c:forEach&
&p&&a href=&${pageContext.request.contextPath}/index.html&&Home page&/a&&/p&
“Edit team” page:
&h1&Edit team page&/h1&
&p&Here you can edit the existing team.&/p&
&p&${message}&/p&
&form:form method=&POST& commandName=&team& action=&${pageContext.request.contextPath}/team/edit/${team.id}.html&&
&td&Name:&/td&
&td&&form:input path=&name& /&&/td&
&td&Rating:&/td&
&td&&form:input path=&rating& /&&/td&
&td&&input type=&submit& value=&Edit& /&&/td&
&/form:form&
&p&&a href=&${pageContext.request.contextPath}/index.html&&Home page&/a&&/p&
And a screenshot of the “List of teams” page:
Integration of several technologies is usually not easy work, so be patient to achieve a success in this. There isn’t a lot of sources in the post, so you can visit my
to explore classes in which you are interested.
About The Author
Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog
Related Posts解决springmvc+mybatis+mysql中文乱码问题
转载 & & 投稿:hebedich
这篇文章主要介绍了解决java中springmvc+mybatis+mysql中文乱码问题的相关资料,需要的朋友可以参考下
近日使用ajax请求springmvc后台查询mysql数据库,页面显示中文出现乱码
最初在mybatis配置如下
&select id="queryContentById" resultType = "java.lang.String" parameterType="String" &
select text from News where id=#{o}
其中表News的text字段为blob类型
如此查出的text值在控制台中一直显示乱码。
之后google查找相关resultType=blob相关内容无果,遂将其改为resultType = "java.util.Map" ,且
byte[] b = (byte[]) map.get("text");
String s = new String(b,"utf-8");
打印出s,此时中文正常显示,但页面显示依旧乱码。
因此处为ajax请求,遂检查响应头信息,查出如下
Content-Typetext/charset=ISO-8859-1
由于数据库中统一为编码为utf-8,故修改响应头信息
@RequestMapping(value = "/queryContentById", method = RequestMethod.GET,produces = "text/charset=UTF-8")
public @ResponseBody String queryContentById(@RequestParam("id") String id) throws SQLException, UnsupportedEncodingException {
Map map = (Map) ndrService.queryContentById(id);
byte[] b = (byte[]) map.get("text");
String s = new String(b,"utf-8");
我们再来看下另外一个示例的问题
1、SpringMVC的Controller得到的是乱码:
(1)在web.xml加上字符集过滤器:
代码如下:&&!-- Spring字符集过滤器 --&&&filter&&&&filter-name&SpringEncodingFilter&/filter-name&&&&filter-class&org.springframework.web.filter.CharacterEncodingFilter&/filter-class&&&&init-param&&&&&param-name&encoding&/param-name&&&&&param-value&UTF-8&/param-value&&&&/init-param&&&&init-param&&&&&param-name&forceEncoding&/param-name&&&&&param-value&true&/param-value&&&&/init-param&&&/filter&&&filter-mapping&&&&filter-name&SpringEncodingFilter&/filter-name&&&&url-pattern&/*&/url-pattern&&&/filter-mapping&
(2)在JSP等页面上修改:charset=UTF-8"和pageEncoding="UTF-8"
2、Controller读取到的是正确的中文,但是保存到数据库后变成“??”
(1)修改数据库连接jdbc_url=jdbc:mysql://localhost:3306/mybatistest?useUnicode=yes&characterEncoding=UTF8("&":在xml文件中表示"&")
(2)修改数据库的字符集为utf-8:打开mysql根目录下my.ini(mysql5.6为my-default.ini,要把它copy一份命名为my.ini),在下面具体位置添加(或修改):
代码如下:[mysqld]character-set-server=utf8 [client]default-character-set = utf8[mysql]default-character-set = utf8
这样设置在我这边就没什么问题了。
通常中文乱码问题都是由于字符编码设置不对导致的,我这里无论是数据库还是java文件、jsp文件,都统一成UTF-8。最后问题解决了。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具博客分类:
public class Vote {
private Set&VoteItem& voteI
private VoteSubject voteS
public class VoteItem {
@RequestMapping
public String vote(@FormModel("votes") Set&Vote& votes) {
System.out.println(votes);
return "";
@FormModel注解请参考《》。
当我们在地址栏输入如:http://localhost:9080/es-web/vote?votes[0].voteItems[0].content=123时,会报:
org.springframework.beans.InvalidPropertyException: Invalid property 'voteItems[0]' of bean class [com.sishuok.es.test.Vote]: Cannot get element with index 0 from Set of size 0, accessed using property path 'voteItems[0]'
原因很明显,Set是无序列表,所以我们使用有顺序注入是不太合适的,BeanWrapperImpl实现:
else if (value instanceof Set) {
// Apply index to Iterator in case of a Set.
Set set = (Set)
int index = Integer.parseInt(key);
if (index & 0 || index &= set.size()) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Cannot get element with index " + index + " from Set of size " +
set.size() + ", accessed using property path '" + propertyName + "'");
Iterator it = set.iterator();
for (int j = 0; it.hasNext(); j++) {
Object elem = it.next();
if (j == index) {
从实现上可以看出,如果set里边有值,那么就能实现绑定。
4、解决方案:
只要保证在springmvc绑定数据之前,给Set里边加上数据即可:
@ModelAttribute("votes")
public Set&Vote& initVotes() {
Set&Vote& votes = new HashSet&Vote&();
Vote vote = new Vote();
votes.add(vote);
vote.setVoteItems(new HashSet&VoteItem&());
vote.getVoteItems().add(new VoteItem());
这样我们就可以把votes暴露给之前的@FormModel("votes") ,它会使用这个来绑定,所以就有数据了。@ModelAttribute方法请参考《》。
但是缺点也很明显,前台必须告诉后台,Set里有几个数据,好让@ModelAttribute方法准备好那么多数据用于数据绑定,比较麻烦。
更简单的解决方案就是使用有序集合,如List,这样最简单。
如上方案通用适用于@ModelAttribute的绑定。
最新的@FormModel的实现请到下载。
相关文章:
浏览 13841
lz分析问题的精神值得佩服! ,对于自己熟悉的领域,就想把问题整明白,整不明白心里走放不下。估计这就是兴趣吧,哈哈。
jinnianshilongnian
浏览量:1891373
浏览量:2388527
浏览量:4890785
浏览量:191883
浏览量:1366839
浏览量:200921
浏览量:4403974
浏览量:523516
浏览量:566772
gududed 写道用testFirstOneSuccessf ...
用例子中的nginx的配置文件,会报404,配置文件中loca ...
lvyuan1234 写道找不到验证码接口的,统统在pom文件 ...
zhaoaij 写道请问:jcaptcha我能找到,就是找不到 ...
找不到验证码接口的,统统在pom文件中加载这个依赖:&d ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'}

我要回帖

更多关于 springmvc整合shiro 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信